过滤Typescript中的现有对象属性

时间:2019-01-23 18:10:10

标签: javascript typescript interface graphql

我在打字稿中有一个any对象,我需要对其进行调整以使其对于给定的接口有效。

我需要一种方法来创建新对象,以清除不属于类定义的属性,并添加缺少的属性。

代码示例可以是:

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

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

我的问题是:有没有一种方法可以转换/过滤myObject,使其适合接口ImyInterface的定义,并转换为该格式

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

1 个答案:

答案 0 :(得分:1)

也许有一种更好的方法,但是这很有效:

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

第一行定义了所需接口的对象。

第二行定义了所需接口的新对象,并将otherObject的所有属性,然后是myObject的符合该接口的所有属性复制到该对象中。

注意:如果您仅尝试使用此方法:

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

您将看到一个错误,指出缺少接口的某些属性。因此,首先创建“完整”对象的原因(在我的示例中为otherObject)。