我只想分享与TypeScript装饰者的短暂斗争的结果。
我试图从属性装饰器中更改属性描述符,例如为了使财产可以实现:
export function MyPropDecorator<T>(options: {enumerable: boolean, <other options...> }) {
return function (target: any, key: string): any {
let type = Reflect.getMetadata("design:type", target, key);
let pd = Object.getOwnPropertyDescriptor(target, key);
pd.enumerbale = options.enumerable;
Object.defineProperty(target, key, pd);
...
}
}
但是只要装饰器功能被移除,“可数”就会以某种方式变回“假”。问题是一个必须在属性装饰器中调用“Object.defineProperty”,因为TypeScript“__decorate”函数将覆盖它。 诀窍是返回修改后的属性描述符:
export function MyPropDecorator<T>(options: {enumerable: boolean, <other options...> }) {
return function (target: any, key: string): any {
let type = Reflect.getMetadata("design:type", target, key);
let pd = Object.getOwnPropertyDescriptor(target, key);
pd.enumerbale = options.enumerable;
return pd;
}
}