In TypeScript, decorators provide a way to add both annotations and a meta-programming syntax for classes, methods, properties, or parameters. Decorators are functions that can be used to modify the behavior of these declarations.
Basic Decorator Syntax:Here's a basic structure of a decorator function:
function myDecorator(target: any, propertyKey: string) {
// Modify behavior here
console.log(`Decorating ${propertyKey} of ${target}`);
}
class MyClass {
@myDecorator
myMethod() {
// Method logic
}
}
Types of Decorators:
- Class Decorators: Applied to classes.
- Method Decorators: Applied to methods within a class.
- Property Decorators: Applied to properties within a class.
- Parameter Decorators: Applied to constructor parameters within a class.
function log(target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling method ${key} with args: ${args}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Example {
@log
greet(message: string) {
console.log(`Hello, ${message}!`);
}
}
const instance = new Example();
instance.greet('World');
In this example:
-
log
is a method decorator that intercepts the method execution. -
descriptor.value
contains the original method, and it's replaced with a wrapper function that logs before executing the original method.
To use decorators in TypeScript, ensure that:
-
"experimentalDecorators":
true is set in yourtsconfig.json
file. - The TypeScript version supports decorators (which is generally the case in recent versions).
- Decorators execute from top to bottom when a class is defined, not when instances are created.
- They can accept arguments and return values, allowing them to be highly configurable.
- They're useful for adding logging, validation, and other cross-cutting concerns without modifying the core logic of your classes or methods.
decorators are a powerful feature, but they require understanding their behavior and potential impacts on code execution and maintainability.