In TypeScript,
decorators provide a way to add metadata or behavior to classes, methods, properties, and other declarations at design time. Decorators are applied using the
`@` symbol followed by the decorator function name, which can be defined separately.
To create a custom decorator in TypeScript, you can follow these steps:
Step 1: Define the Decorator Function
Start by defining a function that will serve as your decorator. This function will receive the target (class, property, or method) and any additional arguments you want to pass to the decorator. The decorator function should return a modified version of the target or perform any desired actions.
Here's an example of a decorator function that logs a message before and after invoking a method:
function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with arguments:`, ...args);
const result = originalMethod.apply(this, args);
console.log(`Method ${propertyKey} returned:`, result);
return result;
};
return descriptor;
}
Step 2: Apply the Decorator
Now you can apply the decorator to a class, property, or method. To apply the decorator, use the `@` symbol followed by the decorator function name.
Here's an example of applying the `logMethod` decorator to a class method:
class Example {
@logMethod
greet(name: string) {
return `Hello, ${name}!`;
}
}
In this example, whenever the
`greet` method is called, the decorator will log the method name and its arguments before executing the original method. Afterward, it will log the returned value.
Step 3: Use the Decorated Class or Method
You can now use the decorated class or its methods as usual. When you invoke the decorated method, the decorator's logic will be executed alongside the original method's logic.
const instance = new Example();
instance.greet('John');
Output:
Calling greet with arguments: John
Method greet returned: Hello, John!
That's it! We have successfully created and applied a custom decorator in TypeScript. Decorators provide a powerful way to add behavior to classes, properties, or methods without modifying their implementation directly.
Conclusion:
Using decorators can help you write more expressive and modular code in TypeScript, You can apply decorators to various components and have them automatically execute specific code before, after, or around the execution of the target component. This promotes modular and maintainable code architectures