【发布时间】: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
如果我在Field 的constructor(...) 方法中记录data 的值,它会毫无问题地打印出对象(更改了隐私值),
{
value: '...message...',
name: '...name...',
inline: false
}
但它仍然崩溃。 Embed 构造函数的值是从 websocket 解析的 JSON 对象,因此 Field 构造函数也是如此。
【问题讨论】:
-
什么是 IEmbed?
-
Embed的接口,虽然我只是将websocket中的JSON数据传递给它的构造函数的数据参数。
-
我们知道它是一个接口,但它的定义缺失。至于错误,如果一个字段为空,复制构造函数会像你的那样落下。
标签: typescript