Decorators
Learn how decorators let you annotate and modify classes, methods, and properties using a concise syntax.
Reading Time
16 min
Lesson
Lesson 28 of 30
What is a Decorator?
A decorator is a function applied to a class, method, property, or accessor using @ syntax, letting you observe, modify, or replace it at definition time — commonly used for logging, validation, and dependency injection.
Enabling Decorators
Decorators are a relatively recent, standardized JavaScript proposal that TypeScript supports natively. Some frameworks (like older Angular versions) rely on the earlier experimental decorator implementation, enabled via a compiler flag.
Enabling the Legacy Experimental Decorators
{
"compilerOptions": {
"experimentalDecorators": true
}
}A Class Decorator
function Logger(constructor: Function) {
console.log(`Class created: ${constructor.name}`);
}
@Logger
class UserService {
// ...
}
// Logs "Class created: UserService" when the class is definedA Method Decorator
A method decorator can wrap a method’s behavior — for example, logging every call along with its arguments and result.
A Method Decorator (Log Calls)
function LogCall(originalMethod: any, context: ClassMethodDecoratorContext) {
return function (this: any, ...args: any[]) {
console.log(`Calling ${String(context.name)} with`, args);
return originalMethod.apply(this, args);
};
}
class Calculator {
@LogCall
add(a: number, b: number): number {
return a + b;
}
}
new Calculator().add(2, 3); // logs the call, then returns 5Decorator Factories
A decorator factory is a function that returns a decorator, letting you pass configuration options into the decorator itself.
A Decorator Factory
function MinLength(length: number) {
return function (value: string): boolean {
return value.length >= length;
};
}
const isValidPassword = MinLength(8);
isValidPassword("short"); // falseWhere Decorators Are Commonly Used
Decorators are most visible in frameworks like Angular (@Component, @Injectable) and NestJS (@Controller, @Get) — you’ll encounter them constantly as a consumer of these frameworks, even if you rarely write your own.
Best Practice
Decorators are powerful but add a layer of indirection that can be hard to follow. Use them where a framework expects them, but avoid inventing custom decorators in application code unless the abstraction genuinely simplifies things.