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

问题描述 投票:0回答:1

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

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'

angular typescript angular7
1个回答
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]};
}
© www.soinside.com 2019 - 2024. All rights reserved.