[英]How to express type for output class of the TS decorator
以下代码来自 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
如何表达装饰的 class 的类型?
更准确地说,我希望智能感知看到g.newProperty
There is another concept called mixin
, a function that returns modified class TypeScript is able to suggest correct props for the returned type of the class
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 */);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.