The following code is from the TS docs
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
How do I express the type for the for the decorated class?
To be more exact, I want intellisense to see the 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 */);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.