代码之家  ›  专栏  ›  技术社区  ›  Carlos Delgado

筛选Typescript中的现有对象属性

  •  0
  • Carlos Delgado  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前
        1
  •  1
  •   DeborahK    6 年前

    可能会有 好吧,但我脑子里的想法是这样的:

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

    第二行定义所需接口的新对象,并将所有属性从 otherObject 然后是来自 myObject

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

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

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