How can I add a new property to a class using a class decorator?
Code for example:
@MyClassDecorator
class MyClass {
myFirstName: string;
myLastName: string;
}
// I need something like this:
function MyClassDecorator (target: any): any {
target['myNickname'] = 'Gambler';
}
let myClass = new MyClass();
console.log(myClass['myNickname']); // expecting "Gambler" but got "undefined"
How to fix this code?
Is it possible at all to add a property to a class using decorator?
Thanks!
You need to add the property to the prototype and not the constructor:
function MyClassDecorator(target: any): any {
target.prototype.myNickname = "Gambler";
}
That will get you what you want, but the problem is that you won't be able to access this property without typescript complaining:
let myClass = new MyClass();
console.log(myClass.myNickname); // error: Property 'myNickname' does not exist on type 'MyClass'
You can try something like:
function myClassFactory(): MyClass & { myNickname: string } {
return new MyClass() as MyClass & { myNickname: string };
}
let myClass = myClassFactory();
console.log(myClass.myNickname); // all good
(code in playground)
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