TypeScript Reference ยท Classes, Enums and Decorators
TypeScript decorator factories
Reference for TypeScript decorator factories: functions that take options and return a decorator, evaluation versus application order, typing and stacking.
A decorator factory is an ordinary function that takes configuration and returns a decorator. You use it with parentheses: @retry(3). Without parentheses (@retry) the decorator syntax passes the class member to your function directly, which is a different call.
Factories exist because the @ syntax itself cannot take arguments. Everything you want to configure goes through the closure of the outer function.
function tag(name: string) { return function (target: Function, context: ClassDecoratorContext): void { console.log(`${name}: ${String(context.name)}`); }; } @tag("model") class User {}
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
function factory(options: Options) { return function decorator(value: Target, context: Context): Result | void { // use options here }; }
| Name | Description |
|---|---|
options |
Whatever you want to configure; available to the inner function through the closure. |
| Inner function | A normal decorator for the member kind: class, method, field, accessor. |
Returns: the decorator. The outer call happens when the class is being defined.
Usage notes
- Order: with stacked decorators the factory calls are evaluated top to bottom, but the resulting decorators are applied bottom to top, as the second example prints.
- Forgetting the parentheses is a common mistake:
@retrypasses the method toretryastimes, which fails type checking. - Factories can be generic and share state through closure variables, but remember the closure is created once per decoration, not once per instance.
- A factory can return one of several decorator shapes based on its options, but keep the return type simple or TypeScript will not pick the right overload.
- Return the original
methodwhen the decorator only observes; no wrapper is needed.