1

Say the database returned an object e.g

foo: {bar: 1, baz: 2, quux: 3}

Then I have this interface that only allows the keys:

bar: number;
quux: number;

I want the object foo to transform itself to only have the key/values that the interface allows and get rid of the rest of the key/values. How can I achieve this?

BigBawss
  • 85
  • 12
  • Not exactly a duplicate, but [this](https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings) should help you – bugs May 01 '18 at 14:05
  • Doesn't this only retrieve the keys and not both? – BigBawss May 01 '18 at 14:12

1 Answers1

0

Unfortunately, there's not a direct way to do so, as interfaces disappear at runtime. The quickest way, in my opinion, would be:

interface Interface {
    foo: number;
    quux: number;
}

const { foo, quux } = foo;
const inewOb: Interface = { foo, quux };

Of course, this solution only serves for this interface, because there is no generic solution due to the fact that, as stated, interfaces disappear at runtime, so there isn't a way to list all its properties and extract them from an object.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42