如何在TypeScript装饰器中获取类型数据?

6 decorator typescript

我想访问我想要装饰的变量声明的类型信息:

@decorator
foo: Foo;
Run Code Online (Sandbox Code Playgroud)

从装饰者,我可以以某种方式访问Foo

Nit*_*mer 13

您应该能够这样做,但您需要使用reflect-metadata.

这里有一个例子:TypeScript中的装饰器和元数据反射:从新手到专家,这似乎正是你所追求的:

function logType(target : any, key : string) {
    var t = Reflect.getMetadata("design:type", target, key);
    console.log(`${key} type: ${t.name}`);
}

class Demo{ 
    @logType
    public attr1: string;
}
Run Code Online (Sandbox Code Playgroud)

应打印:

attr1类型:字符串

  • 顺便提一句。为了使 'design:type' 工作,请确保在 tsconfig.json 中添加 `"emitDecoratorMetadata": true` (2认同)