【问题标题】:Typescript cannot set property of undefined打字稿无法设置未定义的属性
【发布时间】:2019-01-25 11:18:15
【问题描述】:

有人能解释一下为什么你不能在 Typescript 中这样做吗?

this.obj.id = 1;
this.obj.str = 'This is string';

但你可以这样做:

this.obj = { id: 1, str: 'This is string'};

【问题讨论】:

  • this.obj 最初是什么?如果您没有定义它,那么您正在尝试在不存在的东西上定义属性。
  • 因为你不能设置undefined的属性。

标签: typescript


【解决方案1】:

这不是你不能做的事情,而是你做错了。 见Stackblitz Demo

我可以像这样使用它来定义:

obj = [];
obj2 = { id: 0, str: '' };
  
this.obj = { id: 1, str: 'This is string' };
this.obj2.id = 1;
this.obj2.str = 'This is string';
console.log(this.obj)
console.log(this.obj2)
  

【讨论】:

  • 谢谢。我已经知道为什么了。您不能设置未定义的属性。所以你应该初始化一个默认值或者空值。
猜你喜欢
  • 2021-01-07
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
相关资源
最近更新 更多