Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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!

like image 330
Zurab-D Avatar asked Dec 06 '16 16:12

Zurab-D


Video Answer


1 Answers

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)

like image 200
Nitzan Tomer Avatar answered Nov 15 '22 08:11

Nitzan Tomer