【发布时间】:2019-07-15 17:39:46
【问题描述】:
在 TypeScript 的装饰器参考页面上,有一段代码片段说明了如何使用类装饰器覆盖构造函数:
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;
}
}
console.log(new Greeter("world"));
在日志中:
class_1 {
property: 'property',
hello: 'override',
newProperty: 'new property' }
到目前为止一切顺利。但是尝试通过点符号访问newProperty 失败:
类型'Greeter'.ts(2339) 上不存在属性'newProperty'
错误,它没有在 VS Code 的提示中列出。可以通过括号表示法访问它,但 TS 警告说
元素隐式具有“任何”类型,因为类型“Greeter”没有索引 signature.ts(7017)
我错过了什么吗?如何以类型安全的方式通过装饰器添加新属性?我希望像普通的类成员一样拥有普通的编译器支持。
【问题讨论】:
标签: typescript decorator mixins