如何使用类装饰器向类添加新属性? [英] 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?
代码示例:
@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"
如何修复此代码?
是否可以使用装饰器向类添加属性?
Is it possible at all to add a property to a class using decorator?
谢谢!
推荐答案
您需要将属性添加到原型而不是构造函数:
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'
您可以尝试以下操作:
function myClassFactory(): MyClass & { myNickname: string } {
return new MyClass() as MyClass & { myNickname: string };
}
let myClass = myClassFactory();
console.log(myClass.myNickname); // all good
(操场上的代码)
这篇关于如何使用类装饰器向类添加新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文