我有一个简单的类,它的属性有物业装饰师 https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Decorators.md#property-decorators应用于它:
class MyClass {
@collectionMember
public myProperty: number[];
// ...
}
以及装饰器函数:
function collectionMember(target: Object, propertyKey: string | symbol): void {
// ...
}
我怎样才能通过额外的装饰器函数的参数?我尝试执行以下操作但无济于事:
class MyClass {
@collectionMember("MyProp")
public myProperty: number[];
// ...
}
显然,这会产生错误
提供的参数与调用目标的任何签名都不匹配。
可以通过使用装饰器工厂来完成。
工厂只是一个函数,它接收您想要的任何参数并返回带有装饰器签名的函数:
// any parameters, even optional ones!
function collectionMember(a: string, b?: number) {
// the original decorator
function actualDecorator(target: Object, property: string | symbol): void {
// do something with the stuff
console.log(a);
console.log(target);
}
// return the decorator
return actualDecorator;
}
然后你就可以按照你描述的那样使用它了。
class MyClass {
@collectionMember('MyProp') // 2nd parameter is not needed for this array
public myProperty: number[] = [1, 2, 3, 4, 5];
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)