【发布时间】:2020-10-12 00:04:00
【问题描述】:
假设我在 JavaScript 中有这些类,我正在尝试将它们转换为 TypeScript:
class Dog {
tags = {
barked: true,
};
}
class Pug extends Dog {
tags = {
...this.tags,
snorted: true,
};
}
const pug = new Pug();
但是,TypeScript 中的相同代码会产生以下错误:
error TS7022: 'tags' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
这里的错误很明显。我在重新定义tags 时使用this,所以TypeScript 很不高兴。
是否有其他方法可以安抚 TypeScript?到目前为止,我想到的唯一方法是按照错误提示进行操作,并明确键入它。然而,在更大的类型定义中,它会变得重复。
归根结底,我的类的属性是定义的键/值对的对象。并且每个子类都扩展了超类的对象并添加了额外的键/值。
【问题讨论】:
-
上面写着
... this.events,你的意思是...this.tags对吧? -
没有。您使用
this并不难过,您没有声明属性的类型(也无法推断)令人难过。是的,明确输入! -
@Jorjon 是的,很抱歉造成混乱。我正在修剪这个玩具示例的实际代码,却不小心留下了那个错误。
标签: javascript typescript class