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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With