首页 > 解决方案 > 过滤 Typescript 中的现有对象属性

问题描述

我在打字稿中有一个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}

标签: javascripttypescriptinterfacegraphql

解决方案


可能有更好的方法,但在我的脑海中这是可行的:

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

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

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

注意:如果你只用这个试试:

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

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


推荐阅读