如何在 TypeScript 装饰器中获取类型数据?
How to get type data in TypeScript decorator?
我想访问我要修饰的变量声明的类型信息:
@decorator
foo: Foo;
我可以通过装饰器以某种方式访问 Foo
吗?
您应该可以做到,但您需要使用 reflect-metadata。
这里有一个示例:Decorators & metadata reflection in TypeScript: From Novice to Expert 这似乎正是您所追求的:
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;
}
应该打印:
attr1 type: String
我想访问我要修饰的变量声明的类型信息:
@decorator
foo: Foo;
我可以通过装饰器以某种方式访问 Foo
吗?
您应该可以做到,但您需要使用 reflect-metadata。
这里有一个示例:Decorators & metadata reflection in TypeScript: From Novice to Expert 这似乎正是您所追求的:
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;
}
应该打印:
attr1 type: String