作者:爱吃肉肉的狼 | 来源:互联网 | 2022-11-21 08:22
我有一个小错误(?)与我的打字稿代码.请参阅以下内容:
class Component {
assertBoolean(): boolean {
return true;
}
}
class DummyComponent extends Component() {
}
const components: Component[] = [ DummyComponent ];
我收到以下打字稿错误:
错误TS2322:类型'typeof DummyComopnent'不能分配给'Component'类型'typeof DummyComponent'中缺少'assertBoolean'属性.
我真的不知道我在那里做错了什么,基本的OOP.
1> Titian Cerni..:
你没有实例化这个类.DummyComponent
在表达式中使用时表示类本身,而不是类的实例.要实例化该类,您需要使用new
运算符:
class Component {
assertBoolean(): boolean {
return true;
}
}
class DummyComponent extends Component {
}
const components: Component[] = [ new DummyComponent() ];
保留您需要使用的类的数组typeof Component
.这表示类的类型(不是类的实例)
const components: (typeof Component)[] = [DummyComponent];
new components[0]()