1

Say I have an object with an indeterminate set of key-value pairs and an Interface that has a specific set of key-type pairs.

Is there an operation I can invoke that will get all key-value pairs from the object that match a key in the Interface?

i.e.

const foo = {a: 1, b:2, c:3, d: 4}

interface Bar {

   a: number;
   d: number;

}

const res = // is there an operation I can perform that will make this equal {a:1, d:4}

Ben Cooper
  • 1,288
  • 2
  • 10
  • 21
  • This is not possible as asked; the type system is [erased](https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types) from the compiled JavaScript, so there is nothing of `Bar` left for you to do anything with `res`. If you see [this answer](https://stackoverflow.com/a/61684563/2887218) to the question this duplicates, you can see a possible approach where you make a runtime array of keys, and you'll get a compiler error if it's wrong. If I translate the code from that answer to your example, I get [this](https://tsplay.dev/WYJezw). – jcalz Mar 30 '21 at 01:41

0 Answers0