Search code examples
typescriptdecorator

How to get type data in 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?


Solution

  • 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