本文介绍了如何在TypeScript装饰器中获取类型数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to be access the type information on a variable declaration that I want to decorate:

@decorator
foo: Foo;

我可以从装饰器中以某种方式访问​​ Foo

From the decorator, can I somehow access Foo?

推荐答案

您应该可以做到,但是您需要使用。

You should be able to do it, but you'll need to use reflect-metadata.

这里有一个示例:,这似乎正是您所追求的:

There's an example here: Decorators & metadata reflection in TypeScript: From Novice to Expert which seems to be exactly what you're after:

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类型:字符串

这篇关于如何在TypeScript装饰器中获取类型数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:23