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 a method’s functionality, 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 decorator’s name 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 the decorator is applied tokey, which is the name of the decorated methoddescriptor, which is an object containing 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 decorator’s name.
Let’s see it by continuing the previous example, seeing how to apply the logMethod decorator to a class method:
class MyClass {
@logMethod
myMethod(arg1: string, arg2: number) {
console.log(`Method myMethod called with arguments ${arg1} and ${arg2}`);
}
}
In this example:
- We apply the
logMethoddecorator to themyMethodmethod of theMyClassclass - When
myMethodis called, the decorator will print a log message before executing the original method’s code.
