如何使用类装饰器向类中添加新属性?
代码例如:
@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"
如何修复此代码?
是否可以使用装饰器向类中添加属性?
谢谢!
答案 0 :(得分:4)
您需要将属性添加到原型而不是构造函数:
function MyClassDecorator(target: any): any {
target.prototype.myNickname = "Gambler";
}
这会得到你想要的东西,但问题是如果没有打字稿抱怨,你将无法访问这个属性:
let myClass = new MyClass();
console.log(myClass.myNickname); // error: Property 'myNickname' does not exist on type 'MyClass'
您可以尝试以下内容:
function myClassFactory(): MyClass & { myNickname: string } {
return new MyClass() as MyClass & { myNickname: string };
}
let myClass = myClassFactory();
console.log(myClass.myNickname); // all good