Decorate a class, member or property to signify its specialty.
Decorators are not available in Javascript but enable us to enhance our Typescript libraries and code. Decorators are experimental features in Typescript at this time.
A decorator is a way to annotate or modify a class, properties, functions or parameters. Decorator is specified against a target class, and has a body that indicates the decorator’s function.
A decorator exists in brought to life in two parts -
-
Define a function to apply against target class, property etc.
1 2 3
function specialpower(meta: any) { // do something }
-
Then, the decorator is specified against the class, member, etc.
1 2 3 4
@specialpower class Human { // .. }
More than one decorator can be applied in one go.
|
|
The functions are evaluated left to right, and then, top to bottom, as applicable. The results are then called from the last evaluation from previous step to the first.
As an example, consider the below decorator to add a new property to the class.
|
|
Next, we specify the decorator against the class.
|
|
We can see the power added to the class without any further action from our end -
|
|
You can see the potential here - we can start adding “stuff” to props, members and classes, and take Typescript to all new levels. But remember - they are experimental and can change.
If you cannot wait to see decorators today - you can always use NestJS or Angular frameworks. They have decorator support built in and people seem to go crazy about them (I am neutral).