Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 354
TheFooProgrammer Avatar asked May 30 '15 01:05

TheFooProgrammer


People also ask

Which decorator is used to identify a class?

Class Decorators The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.

What is a code decorator?

Basically, a decorator takes in a function, adds some functionality and returns it. def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary") Run Code.


1 Answers

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!
like image 107
NYCdotNet Avatar answered Sep 29 '22 12:09

NYCdotNet