在 TypeScript 5 中,属性装饰器的类型定义已更改,并且似乎没有办法获取类的构造函数。
它现在实现了 TC39 提案,其中属性装饰器的第一个参数始终是
undefined
:
type ClassFieldDecorator = (value: undefined, context: {
kind: "field";
name: string | symbol;
access: { get(): unknown, set(value: unknown): void };
static: boolean;
private: boolean;
}) => (initialValue: unknown) => unknown | void;
以前,装饰器函数的第一个参数是类的构造函数:
function myPropertyDecorator(target: Object, propertyKey: string) {
...
}
获取类的构造函数的能力对于某些库非常有用,例如验证库,在类级别上运行并存储每个类的验证图。
新装饰者的建议有哪些选择?
experimentalDecorators
代替新的装饰器?您可以在装饰器的回调函数中访问类实例:
function propDecorator(value: undefined, ctx: ClassFieldDecoratorContext) {
return function (this: any, initialValue: any) {
console.log(this, this.constructor)
return initialValue;
};
}
class C {
@propDecorator x = 1;
}
new C();
确保不使用箭头函数来保留装饰器函数的上下文。