Reputation: 12295
Here's some code on decorators in the TypeScript 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;
}
}
console.log(new Greeter("world"));
However, if you try to use newProperty
you get a transpiler error:
Property 'newProperty' does not exist on type 'Greeter'.
How do you type this so the transpiler knows that newProperty
in fact exists?
Upvotes: 0
Views: 105
Reputation: 249646
Unfortunately decorators can't impact the structure of the type it is used on. You can use the decorator as a simple function and use the result as the class:
const Greeter = classDecorator(class {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
static test ="";
})
var d = new Greeter("world");
console.log(d.newProperty);
Upvotes: 1