typescript - 如何表示 TS 装饰器的输出类的类型
问题描述
以下代码来自 TS 文档
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
const g = new Greeter("world");
console.log(g.newProperty) // =>>>> ERROR for type check, but correct in runtime
如何表达装饰类的类型?
更准确地说,我希望智能感知看到g.newProperty
解决方案
还有一个叫做 的概念mixin
,一个返回修改后的类 TypeScript 的函数能够为类的返回类型建议正确的道具
function Mixin<T extends { new (...args: any[]): object }>(BaseClass: T) {
return class extends BaseClass {
// The following constructor signature is a must for a mixin
// TypeScript error tells it explicitly
constructor(...args: any[]) {
super(...args)
// Additional stuff
}
// Additional functionality here
}
}
class A {}
const ModifiedA = Mixin(A);
const ModifiedAObject = new ModifiedA(/* params */);
推荐阅读
- python - 是否有必要使 uqiue 索引列不可为空(SQL、SQLAlchemy)?
- r - 从特定行获取数据
- python - jinja2.exceptions.TemplateNotFound:index.html
- laravel - Laravel 6.8 返回 404 未找到页面
- swift - 使用滚动视图在 Xcode 11 中缩放图像,避免“不明确的内容大小”自动布局错误
- sql - 如果 2 列具有相同的数据 - Codeigniter,如何比较 SQL 中的两个表?
- python - 如何让电脑用python说话?
- android - 来自 React Native 的 Android App Bundle:您上传的 APK 或 Android App Bundle 的某些文件的签名信息无效或缺失
- android - 为什么我的底部导航视图不显示任何标题或图标?
- python-3.x - 以下 ResNet50 分类模型中验证准确度为 0 的原因