Search code examples
typescripttypescript-decorator

TS. Enumerate the decorators


i have a question - i am trying to write my own realisation of Injectable and i need to know, whether i have specific decorator in my Class or no. How can i enumerate all decorators of class? For example, i have the following code. All i need to know, whether i have "myDecorator" as a decorator in MyClass or nope

function myDecorator(ctor: Function):void{
    console.log(ctor)}

@myDecorator

class MyClass{
    static isInjectable: boolean;
    public a: number = 5;
    constructor() {
        this.a = 5;
    }
}

Maybe, i can use Reflect-API to solve that problem, but i still have no idea how to use it correctly


Solution

  • What you need is to define a decorator like this:

    export function Injectable(constructor: Function): void{
        Reflect.defineMetadata("isInjectable", Injectable, constructor);
    }
    
    export class Injector<T>{
        get(ctor: {new() : T}): T{
            console.log(Reflect.getMetadata("isInjectable", ctor));
                return new ctor();
        }
    }
    

    and afterwards try to get it from the Injector class.