TypeScript Reference ยท Classes, Enums and Decorators
TypeScript accessor decorators
Reference for standard TypeScript accessor decorators: decorating getters, setters and auto-accessor fields, the get/set/init result object and validation examples.
Three kinds of class members behave like accessors, and each has its own decorator shape. A getter or setter decorator receives the function and can return a replacement function. An auto-accessor (accessor x = 0) decorator receives a { get, set } pair and can return { get, set, init } to override any of the three.
Because auto-accessors intercept every read and write, they are the right tool for validation, change tracking and reactive state.
class Box { accessor width = 10; }
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
// auto-accessor type AccessorDecorator<This, V> = ( target: ClassAccessorDecoratorTarget<This, V>, context: ClassAccessorDecoratorContext<This, V>, ) => ClassAccessorDecoratorResult<This, V> | void; // getter / setter type GetterDecorator<This, V> = ( value: (this: This) => V, context: ClassGetterDecoratorContext<This, V>, ) => ((this: This) => V) | void;
| Name | Description |
|---|---|
target |
For auto-accessors: { get, set } functions of the default implementation. |
context.kind |
"accessor", "getter" or "setter". |
Result get / set |
Replacement implementations; omitted parts keep their defaults. |
Result init |
Maps the initial value of an auto-accessor. |
Edge cases: a getter and its setter are decorated separately; the decorators on each only see their own half.
Usage notes
- Throwing from a replacement
setleaves the old value in place, as the output above shows. - Decorating a getter with a cache assumes the value never changes; invalidation is your job.
accessordeclarations are plain JavaScript syntax proposals, and TypeScript lowers them to private fields plus accessors.- Static,
#privateand public forms are all allowed.