0

Lets say I have a type/interface like this:

interface MyInterface {
    memberInTheInterface?: string;
   // ... more members
}

and an object that looks like this:

const myObject = {
    memberInTheInterface: "foo",
    // ... more members that are in the interface
    memberNotInTheInterface: "bar"
    // ... more members that are not in the interface
}

Now I want to get a new object with all the members of myObject except those that are in the type/interface, such that in the end I have an object like this:

{
    memberNotInTheInterface: "bar"
    // ... other members not in the interface
}

I know that you can use the spread operator to exclude certain members from an object like this:

const { memberInTheInterface, ...myNewObject } = myObject;

However, I do not want to statically type out all the member names, and instead use all (including optional) members of a type dynamically. Is this possible and if so how?

I tried to find an answer in the TypeScript manual, via Google and obviously here, but with no avail. Is there some keyword or phrase that would have brought me to an existing answer?

  • you may want to have a look at [this answer](https://stackoverflow.com/questions/50839597/typescript-extract-interface-members-only-possible) – CapitanFindus Sep 02 '21 at 07:58
  • If I understand the most upvoted answer on that question correctly then you have to manually type out all the members in the "extraction method" as well. Which would be just a more sophisticated way of doing object destructuring as I understand it. – TheHelpfulHelper Sep 02 '21 at 08:07
  • types (and so interfaces) are not available at runtime-time, they're just checked at compile-time, so that's why you cannot access them during runtime (in your code), as they're not like normal js objects. the accepted answer's method is perfectly fine but sophisticated, so I'm not really sure why you should implement it. imho, you can simplify by forcing types, so the compiler actually obliges you to remove keys from objects, but you will still need to do it on your own – CapitanFindus Sep 02 '21 at 09:38

1 Answers1

0

You can use this library to get keys from your interface as array of strings: https://github.com/kimamula/ts-transformer-keys

With that it should be fairly easy to filter keys on your object. For the filtering of object properties check this answer: Filter object properties by key in ES6

Martin Mecir
  • 80
  • 1
  • 8