How to get type data in TypeScript decorator?

ⅰ亾dé卋堺 提交于 2020-01-23 05:42:08

问题


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

@decorator
foo: Foo;

From the decorator, can I somehow access Foo?


回答1:


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;
}

Should print:

attr1 type: String



来源:https://stackoverflow.com/questions/38314908/how-to-get-type-data-in-typescript-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!