TypeScript Reference ยท Classes, Enums and Decorators
TypeScript method decorators
Reference for standard TypeScript method decorators: the (method, context) signature, wrapping calls for logging or caching, typing with generics and static and private methods.
A method decorator receives the original method and a ClassMethodDecoratorContext. It usually returns a new function that calls the original, which makes it a tidy place for logging, timing, caching and argument checks. Returning nothing leaves the method as it was.
The wrapper must be a regular function (not an arrow function) so it keeps the this of the call.
function log<This, Args extends unknown[], R>( method: (this: This, ...args: Args) => R, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>, ) { return function (this: This, ...args: Args): R { console.log(`call ${String(context.name)}`); return method.call(this, ...args); }; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type MethodDecorator<This, Fn extends (this: This, ...args: any) => any> = ( value: Fn, context: ClassMethodDecoratorContext<This, Fn>, ) => Fn | void;
| Name | Description |
|---|---|
value |
The original method function. |
context |
kind: "method", name, static, private, access.has/get, addInitializer, metadata. |
Returns: a replacement function with a compatible signature, or void.
Edge cases: the returned function receives the call-time this; arrow functions inside a decorator would capture the wrong one. Static and #private methods can be decorated too; context.private and context.static tell you which.
Usage notes
- Use generics (
This,Args,R) so the decorator is checked against the method it is attached to, as the second example shows. - A decorator that changes the method's signature at run time hides that change from the type system; keep the types honest.
context.addInitializercallbacks run during construction (or class definition for static methods), which is how decorators bind methods to the instance.- Order matters when stacking: the decorator closest to the method wraps first.
- Method decorators cannot decorate overload signatures, only the implementation.