How to get type data in TypeScript decorator?

前端 未结 1 1367
傲寒
傲寒 2021-01-04 12:27

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

@decorator
foo: Foo;

From the decorator,

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 12:48

    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

    0 讨论(0)
提交回复
热议问题