According to the typescript decorators documentation the decorator example for replacing a constructor does not pass any arguments to the decorator function. How am I able to achieve this?
This is what the doc says
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;
}
}
But I want now to pass arguments like using the decorator as follows
@classDecorator({
// some object properties fitting DecoratorData type
})
I simply tried to add a second data parameter
function classDecorator<T extends {new(...args:any[]): {}}>(constructor: T, data: DecoratorData)
But this just tslint 2 arguments required, got 1. Inserting a null
placeholder doesn't work either. Also I tried using the constructor
parameter as a second optional parameter. This leads to a signature missmatch error.
You need to use a decorator generator, a function which returns a decorator function. The generator function can take extra arguments, and the inner decorator function can capture those parameters and use them.
function classDecorator(data: DecoratorData) {
return function <T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
// use daat here
}
}
}
@classDecorator({ data: "" })
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With