How to get type data in TypeScript decorator?

时间:2016-07-11 19:40:25

标签: typescript decorator

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 个答案:

答案 0 :(得分:13)

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