DZN
DZN

Reputation: 1553

How to add a new property to a class using class decorator?

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!

Upvotes: 8

Views: 9183

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

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)

Upvotes: 8

Related Questions