typescripttypescript1.5

How to find all classes decorated with a certain decoration?


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

How can we do something similar in TypeScript? Is there a way to find all classes decorated with some decoration?


Solution

  • Here's an example. It assumes you have some way of referencing the scope. The magical class decorator creates a string property called isMagical on the classes that it's applied to, and assigns the value of it as "indeed". Then the findMagicalInScope() function loops through the properties on the specified scope (which is why the classes are all in a module) and sees if they have an isMagical property.

    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!