简体   繁体   English

过滤Typescript中的现有对象属性

[英]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. 我有一个any的打字稿对象,我需要的形状,它是有效的给定接口。

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 我的问题是:有没有办法转换/过滤myObject ,使其适合接口ImyInterface定义,并转换为

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. 第二行定义了所需接口的新对象,并将otherObject所有属性复制到该对象中,然后将myObject中符合该接口的所有属性复制到该对象中。

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). 因此,首先创建“完整”对象的原因(在我的示例中为otherObject )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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