When using a decorator, it expects an argument which is the target being decorated along with additional arguments based on the type of the target.
For Method Decorators:
The method decorator expression is called as a function during runtime and takes three arguments:
- The constructor function of the class for a static member or the prototype of the class for an instance member.
- The name of the member.
- The Property Descriptor for the member.
You can refer to TypeScript Decorators for a complete list of all decorator types:
Class Decorators
- Applies only to the target class.
Method Decorators
- The constructor function of the class for a static member or the prototype of the class for an instance member,
- The name of the member,
- The Property Descriptor for the member
Accessor Decorators
- The constructor function of the class for a static member or the prototype of the class for an instance member.
- The name of the member.
- The Property Descriptor for the member.
Property Decorators
- The constructor function of the class for a static member or the prototype of the class for an instance member.
- The name of the member.
Parameter Decorators
- The constructor function of the class for a static member or the prototype of the class for an instance member.
- The name of the member.
- The ordinal index of the parameter in the function’s parameter list.
In addition:
If we wish to customize how a decorator is applied to a declaration, we can create a decorator factory. A Decorator Factory is essentially a function that returns the expression to be executed by the decorator at runtime.
[TypeScript Decorators]
You have the freedom to create decorator factories with parameters as needed; there are no limitations or restrictions imposed.
The examples provided are from the TypeScript documentation.
Example of a Decorator:
function sealed(target) {
// perform actions on 'target' ...
}
Applied using:
@sealed x
Example of a Decorator Factory:
function color(value: string) {
// this serves as the decorator factory
return function (target) {
// this represents the actual decorator
// perform actions involving 'target' and 'value'...
};
}
Usage:
@color('blue') x