typescript - 未实例化类的数组的打字稿数据类型
问题描述
我想在 Typescript 类中实现“特征”(如 PHP)功能。我认为下面的代码可以工作,但事实并非如此。我不知道为什么,因为这对我来说很有意义。
interface Trait {
register: (Model: BaseModel, option?: object) => void
}
interface IPrototype {
prototype: any;
}
class Tenable implements Trait {
register(Entity: BaseModel & IPrototype, option = {}) {
Entity.prototype.hello = function () {
console.log('Hello World from Tenable!');
}
}
}
class BaseModel {
protected traits: Trait[] = [];
}
class A extends BaseModel {
protected traits = [Tenable];
}
如果您在 Typescript Playgound 中运行此代码,您会看到错误。打字稿游乐场
解决方案
这意味着一个对象数组Trait
。
protected traits: Trait[] = [];
Trait
但是在这里,您使用对象构造函数创建了一个数组。
protected traits = [Tenable];
要获得构造此类对象的构造函数列表,您需要更改特征类型。
protected traits: (new () => Trait)[] = [];
推荐阅读
- git - git stash pop 也可以切换到原始分支/提交吗?
- csv - Choropleth 地图无法为 geojson 边界渲染着色
- oracle - 包体中有两个同名但参数不同的函数是什么意思?
- mqtt - Node mqtt 2.14.0 vs org.eclipse.paho.client.mqttv3 支持的协议
- security - 链接到非常旧版本的 glibc 会引入安全漏洞吗?
- javascript - 在浏览器或 Node.js 中的 JavaScript 中生成模块导入类
- jquery - 如何在选中复选框时禁用文本框并在未选中复选框时启用它们
- mysql - 如果我在 mysql 上无法访问 root,有什么方法可以获取我的 WP 数据库?
- mysql - 查找最接近指定日期时间的记录
- python - 如何在每个单独的 matshow 子图上显示颜色条