typescript - Typescript 类方法作为属性找到
问题描述
我的打字稿代码有一个小错误(?)。请参阅以下内容:
class Component {
assertBoolean(): boolean {
return true;
}
}
class DummyComponent extends Component() {
}
const components: Component[] = [ DummyComponent ];
我收到以下打字稿错误:
错误 TS2322:类型 'typeof DummyComopnent' 不可分配给类型 'Component' 类型 'typeof DummyComponent' 中缺少属性 'assertBoolean'。
我真的不知道我在那里做错了什么,基本的OOP。
解决方案
您没有实例化该类。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]()
推荐阅读
- node.js - Angular 6 文件上传
- sql-server - 列出 SQL Server 表元数据
- mysql - 从数据库加载命令
- sql - 我们如何在 SELECT 子句中使用子查询重写查询?
- node.js - 对图像使用旋转会导致带有 pdfkit 的空白 pdf
- jquery - ASP MVC Ajax 状态 200 但解析器错误
- angular - Angular 2 将值从选择器传递到 html 模板
- javascript - 将值插入到预定义的反引号模板文字字符串中?
- python - python聚合groupby使用默认函数
- jquery - 悬停在相邻元素之外后,无法防止按钮消失