Decorators with TypeScript
All posts in TypeScript series:
or via parameters through tsc CLI.
tsc --target ES5 --experimentalDecorators
Simple method decorator:
target parameter is either constructor function or the prototype of the class for an instance member, propertyKey is the name of the method, descriptor is the property descriptor.
As a result of executing previous code we get the following output:
You can assign multiple decorators to a declaration:
Here is the output:
As you can see, expressions for decorators are applied from top to bottom, while results are called as functions in reverse order – from bottom to top. It is important to notice that we got the output here without making an instance of Test class and calling the method appendTextToName explicitly. That is because our decorator functions (
c ) are executed at runtime.
Lets sum up what we have learned about decorators so far:
- Proposed feature for future version of JS
- Declarative programming
- They are functions
- You can apply multiple decorators to a declaration
- You can apply them to:
You can find the code at https://github.com/Ibro/typescript-decorators