Decorator
Example
function withLogging(fn) {
return (...args) => {
console.log(fn.name, args);
fn(...args);
};
}function withLogging(fn) {
return (...args) => {
console.log(fn.name, args);
return fn(...args);
};
}The wrapper must return the wrapped result, or every decorated function silently returns undefined.
Common mistakes
- A wrapper that forgets to return the result, so the function returns
undefined. - Timing an async function without
await, so the measurement ends before the work does.
Key points
- The wrapper returns the wrapped function's result and passes all arguments through.
- The wrapper keeps the same interface as the original, so decorators can be stacked.
- Async functions are awaited inside the wrapper when it runs code after the call.
Interview questions
Is the Decorator pattern the same as TypeScript decorators?
No. TypeScript @decorator is syntax for wrapping classes and members. It can implement the pattern, but the pattern also works with plain wrapper functions.
Decorator vs inheritance: when should I use which?
Use a decorator to add behavior to individual objects at runtime or to combine features freely. Inheritance fixes behavior at class definition and grows a class per combination.
Are higher-order components decorators?
Yes, in spirit. A higher-order component wraps a component and returns a new one with extra props or behavior, keeping the same rendering interface.