Decorators in TypeScript are a syntax for special functions that are applied to a class, method, property, or parameter to modify or add additional behaviors.
These functions are executed at compile time and can perform tasks such as modifying the functionality of a method, tracking method calls, validating input parameters (among many other things)
Creating a Basic Decorator
To create a decorator in TypeScript, we simply need to define a function with the name of the decorator and apply it to the class, method, property, or parameter we want to decorate. For example,
function logMethod(target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Method ${key} called with arguments ${args}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
In this example, we define a function called logMethod
that takes three parameters:
target
, which is the class to which the decorator is appliedkey
, which is the name of the decorated methoddescriptor
, which is an object that contains information about the decorated method
On the other hand, in the body of this function
- We save a reference to the original method
- We redefine the method to print a log message before calling the original method
- Finally, we return the modified descriptor
Applying a Decorator
Once we have created our decorator, we can apply it to the class, method, property, or parameter we wish to decorate using the @
symbol followed by the name of the decorator.
Let’s see this by continuing the previous example, showing how to apply the logMethod
decorator to a method of a class:
class MyClass {
@logMethod
myMethod(arg1: string, arg2: number) {
console.log(`Method myMethod called with arguments ${arg1} and ${arg2}`);
}
}
In this example,
- We apply the
logMethod
decorator to themyMethod
of theMyClass
- When
myMethod
is called, the decorator will print a log message before executing the original method’s code.