【问题标题】:"Cannot read property 'name' of undefined" when it should be defined“无法读取未定义的属性'名称'”何时应该定义
【发布时间】:2021-11-18 22:52:02
【问题描述】:
interface IField {
  readonly name : string;
  readonly value : string;
  readonly inline ?: boolean;
}

class Field implements IField {
  readonly name : string;
  readonly value : string;
  readonly inline ?: boolean;

  constructor(data : IField) {
    this.name = data.name;
    this.value = data.value;
    this.inline = data.inline;
  }
}

当尝试在另一个类中从Field 类初始化一个新变量时,

class Embed implements IEmbed {
  ...

  constructor(data : IEmbed) {
    ...

    this.fields = data.fields.map((field) => new Field(field));

    ...
  }
}

我的程序因错误而崩溃,

        this.name = data.name;
                         ^

TypeError: Cannot read property 'name' of undefined

如果我在Fieldconstructor(...) 方法中记录data 的值,它会毫无问题地打印出对象(更改了隐私值),

{
  value: '...message...',
  name: '...name...',
  inline: false
}

但它仍然崩溃。 Embed 构造函数的值是从 websocket 解析的 JSON 对象,因此 Field 构造函数也是如此。

【问题讨论】:

  • 什么是 IEmbed?
  • Embed的接口,虽然我只是将websocket中的JSON数据传递给它的构造函数的数据参数。
  • 我们知道它是一个接口,但它的定义缺失。至于错误,如果一个字段为空,复制构造函数会像你的那样落下。

标签: typescript


【解决方案1】:

最终使用了this question 的解决方案。

class Field implements IField {
  readonly name : string;
  readonly value : string;
  readonly inline ?: boolean;

  constructor(data : Partial<Field> = {}) {
    Object.assign(this, data);
  }
}

我用data : Partial&lt;Field&gt; = {} 替换了data : any 部分,为该字段提供了默认值。感谢 Wiktor 引导我朝着正确的方向前进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2022-01-22
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    • 2017-02-06
    相关资源
    最近更新 更多