Modern Decorators
Intercepting and wrapping methods.
Declarative Wrappers
A decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.
In TypeScript 5.0+, decorators are standard (not experimental). They are simply functions that intercept the target they are attached to, allowing you to wrap or modify it.
Cross-Cutting Concerns
Imagine you want to log the execution time of 50 different methods across your app.
Instead of writing console.time() inside every single method, you can write one @time decorator and stick it on top of any method you want!
Syntax (TS 5.0+)
typescript
// The decorator function
function logged(originalMethod: any, context: ClassMethodDecoratorContext) {
return function (this: any, ...args: any[]) {
console.log(Calling ${String(context.name)} with args:, args);
return originalMethod.call(this, ...args);
};
}
class Calculator {
@logged
add(a: number, b: number) {
return a + b;
}
}
const calc = new Calculator();
calc.add(2, 3); // Logs: "Calling add with args: [2, 3]"
Try it
Watch how a @logged decorator wraps a class method, intercepting the call to inject its own logic before running the original method.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Decorators use the
@syntax. - TS 5.0 standard decorators are different from the old experimental ones.
- Method decorators return a replacement function to wrap the original.
- They are perfect for logging, timing, auth checks, and memoization.
Done with this concept?
Mark it complete to track your progress. No login needed.