Carlos Delgado
Carlos Delgado

Reputation: 562

Filter existing object properties in Typescript

I have an any object in typescript which I need to shape so it is valid for a given interface.

I need a way to create the new object in a way that cleans out the properties which don't belong to the class definition, and adds the missing properties.

A code sample could be:

interface ImyInterface {
  a: string;
  b: string;
  c?:string;
};

let myObject = {
  a: "myString",
  d: "other value"
};

My question is: is there a way to convert/filter myObject so it fits the interface ImyInterface definition, and gets transformed to this

console.log (JSON.stringify(objectA));
> {a: 'myString', b: null}

Upvotes: 1

Views: 1815

Answers (1)

DeborahK
DeborahK

Reputation: 60626

There may be a better way, but off the top of my head this works:

    let otherObject: ImyInterface = { a: null, b: null };
    let x: ImyInterface = { ...otherObject, ...myObject };

The first line defines an object of the desired interface.

The second line defines a new object of the desired interface and copies into that object all of the properties from otherObject and then any properties from myObject that conform to the interface.

NOTE: If you try it just with this:

let x: ImyInterface = { ...myObject };

You will see an error that some of the properties for the interface are missing. Hence the reason to create a "complete" object first (otherObject in my example).

Upvotes: 2

Related Questions