TypeScript 5 - 从属性装饰器访问类构造函数

问题描述 投票:0回答:1

在 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) { 
  ...
}

获取类的构造函数的能力对于某些库非常有用,例如验证库,在类级别上运行并存储每个类的验证图。

新装饰者的建议有哪些选择?

  1. 在初始化函数中获取类构造函数?
  2. 使用
    experimentalDecorators
    代替新的装饰器?
  3. 还有什么吗?
typescript ecmascript-next typescript-decorator typescript-5
1个回答
0
投票

您可以在装饰器的回调函数中访问类实例:

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();

确保不使用箭头函数来保留装饰器函数的上下文。

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.