动态创建和分配对象属性打字稿

时间:2020-04-21 19:45:48

标签: angular typescript angular7

我有一个这样声明的接口,

export interface OurHistory {
  ourHistory?: object;
  step1?:object;
  step2?:object;
}

在教室里,我有

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory:OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory.ourHistory = ourHistory[0];
}

我收到一条错误消息:无法设置未定义的属性“ ourHistory”

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为在倒数第二行上:this.myHistoryundefined。您正在尝试访问编译器不喜欢的ourHistory的属性undefined

您需要实例化属性,如问题注释中所述。

一种实现方式,可以这样做:

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory: OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory = {ourHistory: ourHistory[0]};
}

这样,我们用新对象实例化属性myHistory

{
   ourHistory: someValue
}