Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...