TypeScript Decorators
Decorators are a special kind of declaration that can be attached to classes, methods, properties, or parameters to add extra behavior or metadata, using an `@expression` syntax.
Decorators are commonly used in frameworks like Angular and NestJS to add functionality such as dependency injection or routing information. They require enabling `experimentalDecorators` in tsconfig.json.
function Logger(target: Function) {
console.log(`Class created: ${target.name}`);
}
@Logger
class MyClass {}Class decorators
A class decorator is a function that receives the class constructor and can observe, modify, or replace it, applied by writing `@decoratorName` right above the class declaration.
Method decorators
A method decorator can wrap or modify how a method behaves, such as logging every time it's called, by receiving the target, method name, and property descriptor.
function Logger(target: Function) {
console.log(`Class created: ${target.name}`);
}
@Logger
class Greeter {
greet() {
return "Hi!";
}
}Class created: GreeterThe Logger decorator runs once when the Greeter class is defined, logging its name.
function LogMethod(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${key}`);
return original.apply(this, args);
};
}
class Calc {
@LogMethod
add(a: number, b: number) {
return a + b;
}
}
console.log(new Calc().add(2, 3));Calling add
5The method decorator wraps add() to log a message every time it's called.
Key points
- Decorators use `@expression` syntax above a declaration.
- They can be applied to classes, methods, properties, and parameters.
- Decorators require enabling experimentalDecorators in tsconfig.json.
- Frameworks like Angular and NestJS rely heavily on decorators.
