首页 > 解决方案 > 编辑接口类型变量的属性

问题描述

假设我有以下界面:

  export interface MyInterfaceType{
        field1: string;
        field2: string;
        field3: string;
        field4: number;
        field5: string;
        field6: string;
        field7: string;
        field8: string;
        field9: number;
  }    

现在假设我有以下temp变量:

let temp: MyInterfaceType = someVariableOfType_MyInterfaceType as MyInterfaceType;

在上面我不能直接编辑temp下面的属性

temp.field5 = xxxxxx // doesnt work

因为我会得到“无法分配给对象的只读属性'field5'”

为了绕过这个问题,我执行以下操作:

  let finalObject: MyInterfaceType = {
    field1:temp.field1,
    field2:temp.field2,
    field3:temp.field3,
    field4:temp.field4,

    field5:xxxxxx, // something random

    field6:temp.field6,
    field7:temp.field7,
    field8:temp.field8,
    field9:temp.field9
  };

在类似情况下是否有更简洁的方法来编辑接口类型的属性?

标签: typescripttypescript-typingstypescript2.0

解决方案


推荐阅读