首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Reflect.decorate VS在TypeScript中手动装饰

Reflect.decorate VS在TypeScript中手动装饰
EN

Stack Overflow用户
提问于 2019-08-07 18:23:00
回答 1查看 365关注 0票数 1

我有两个装饰器,如下:

代码语言:javascript
运行
复制
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);
}

一种是手动应用的:

代码语言:javascript
运行
复制
export class MyClass {
  @Decorator1
  private foo: string;
}

另一种使用Reflect.decorate

代码语言:javascript
运行
复制
Reflect.decorate([Decorator2], MyClass, "foo");

为什么使用Reflect应用的装饰器不能检索数据类型?

日志输出为:

代码语言:javascript
运行
复制
Applied Decorator1 to foo on MyClass
String

Applied Decorator2 to foo on MyClass
undefined
EN

Stack Overflow用户

回答已采纳

发布于 2019-08-07 20:18:19

要使用Reflect.decorate实现类似的行为,您必须传递类的原型。

代码语言:javascript
运行
复制
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

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57392210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档