How do I find all of the classes with a specific decoration?

In Java, we can find all classes that have a given annotation using "trajectory scanning".

How can we do something like this in TypeScript? Is there a way to find all the classes that are decorated with some kind of decoration?

+3


source to share


2 answers


Here's an example. It assumes that you have a way to reference the scope. The class decoder magical

creates a string property isMagical

for the classes to which it applies and assigns a value to it as "valid". The function then findMagicalInScope()

goes through the properties of the specified scope (so the classes are all in the module) and see if they have a property isMagical

.

module myContainer {

  @magical
  export class foo {
  }

  export class bar {
  }

  @magical
  export class bas {
  }
}


function magical(item: any) {
  item.isMagical = "indeed";
}

function findMagicalInScope(theScope: any) {
  for(let prop in theScope) {
    if (theScope[prop]["isMagical"]) {
        console.log(`Is ${prop} magical?  ${theScope[prop]["isMagical"]}!`);
    } else {
      console.log(`${prop} is not magical.  :-(`);
    }
  }
}

findMagicalInScope(myContainer);

      



Will generate this output when run in Node.js:

Is foo magical?  indeed!
bar is not magical.  :-(
Is bas magical?  indeed!

      

+5


source


The correct way is to populate a static collection from a decorator handler.



-1


source







All Articles