Ivan Mjartan Ivan Mjartan - 2 months ago 8
Javascript Question

Get all classes/constructors by given @decorators

Hi all I am wonder if that is possible get all classes that have given decorator javascript/typescript.

I have class for example

@mydecorator
class SomeClass1{
}


and somewere else in module

@mydecorator
class SomeClass2{
}


then in other module in runtime i would like to get all classes or constructors that have decorator @mydecorator ... I am afraid that this is not possible :(

export function getaAllClassesByDecorator(decorator:string){
... return constructor or something that i am able to call static method
}

Answer

You need to "register" all classes that uses @mydecorator somewhere. This register logic should be implemented in @mydecorator. For example:

export const registeredClasses = [];
export function mydecorator() {
     return function(target: Function) {
          registeredClasses.push(target);
     };
}

@mydecorator()
class SomeClass1{
}

@mydecorator()
class SomeClass2{
}

Now you can get all registered classes in the registeredClasses array