I want to create a decorator that adds a method to a class.
export function Deco() {
return function<T extends { new (...args: any[]): {} }>(constructor: T) {
constructor.prototype.someMethod = function() {
};
};
}
@Deco()
class Test {
}
The problem is when I'm trying to invoke the added method, I am getting typescript error:
Property someMethod does not exist on type Test.
const test = new Test();
test.someMethod();
How can I solve this issue?
Decorators can't influence the structure of the type. There is a simple workaround to this. Invoke the decorator with the class, and inside the function create a derived class with the methods you want. The result of the function will the new "decorated" class and it will have all the methods:
export function Deco() {
return function <T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
someMethod() {
}
}
};
}
let Test = Deco()(class {
// Other stuff
});
const test = new Test();
test.someMethod();
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