简体   繁体   中英

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}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM