我有两个装饰器,如下:
import "reflect-metadata";
const enum MetadataTypes {
  Type = "design:type",
  Paramtypes = "design:paramtypes",
  ReturnType = "design:returntype"
}
function Decorator1(target: any, key: string): void {
  console.log(`Applied Decorator1 to ${key} on ${target.constructor.name}`);
  const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
  console.log(type.name);
}
function Decorator2(target: any, key: string): void {
  console.log(`Applied Decorator2 to ${key} on ${target.name}`);
  const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
  console.log(type);
}一种是手动应用的:
export class MyClass {
  @Decorator1
  private foo: string;
}另一种使用Reflect.decorate
Reflect.decorate([Decorator2], MyClass, "foo");为什么使用Reflect应用的装饰器不能检索数据类型?
日志输出为:
Applied Decorator1 to foo on MyClass
String
Applied Decorator2 to foo on MyClass
undefined发布于 2019-08-07 20:18:19
要使用Reflect.decorate实现类似的行为,您必须传递类的原型。
import "reflect-metadata";
const enum MetadataTypes {
  Type = "design:type",
  Paramtypes = "design:paramtypes",
  ReturnType = "design:returntype"
}
function Decorator1(target: any, key: string): void {
  console.log(`Applied Decorator1 to ${key} on ${target.constructor.name}`);
  const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
  console.log(type.name);
}
export class MyClass {
  private foo: string;
}
Reflect.decorate([Decorator1], MyClass.prototype, "foo");
// Output:
// Applied Decorator1 to foo on MyClass
// undefined问题是在使用Reflect.decorate时不会生成元数据。
使用装饰器语法使编译器保存可通过Reflect.getMetadata访问的元数据(当启用了emitDecoratorMetadata配置选项时)。
你可以在这里阅读到:https://github.com/Microsoft/TypeScript/issues/2577
https://stackoverflow.com/questions/57392210
复制相似问题