Decorators in Typescript
Decorators in Typescript
Class Decorators
Class decorators are used to modify the class definition. They can be used to add properties, methods, or static properties to the class.
@myDecorator(param)
class MyClass {
// class definition
}
The @myDecorator(param)
is a class decorator. It takes a parameter param
and modifies the class definition.
Decorator Factory
Decorator Factory is a function that returns a decorator function. The decorator function can be used to modify the class or property.
function myDecorator(param: any) {
return function (target: any) {
// modify the target
}
}
}
The myDecorator
function takes a parameter param
and returns a decorator function. The decorator function takes a target as its argument and modifies it.
If there are multiple decorator factories, they can be applied in the order they appear. Decorator factories are applied first from up to down. After all decorators are acquired, decorators are applied from down to up.
@myDecorator1(param1)
@myDecorator2(param2)
class MyClass {
// class definition
}
In this example, myDecorator1
is applied first, then myDecorator2
.
Property Decorators
Property decorators are used to modify the properties of a class. They can be used to add getters, setters, or static properties to the properties.
function myDecorator(param: any) {
return function (target: any, propertyKey: string) {
// modify the property
}
}
class MyClass {
@myDecorator(param)
myProperty: string;
}
The @myDecorator(param)
is a property decorator. It takes a parameter param
and modifies the myProperty
property.
The target is the class for static properties, and for instance properties, it is the prototype object of the class. The propertyKey is the name of the property.
Method Decorators
Method decorators are used to modify the methods of a class. They can be used to add logging, caching, or validation to the methods.
function myDecorator(param: any) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
// modify the method
}
}
class MyClass {
myMethod(@myDecorator(param) param1: string, param2: number) {
// method definition
}
}
The @myDecorator(param)
is a method decorator. It takes a parameter param
and modifies the myMethod
method. The target is the class for static properties, and for instance properties, it is the prototype object of the class. The propertyKey is the name of the property. Descriptor is the property descriptor of the method, value is the method itself.