Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
class Box {
  accessor width = 10;
}

Try it

TypeScript Validating an auto-accessor

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.

TypeScript Decorating a getter

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

TypeScript
// 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 set leaves 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.
  • accessor declarations are plain JavaScript syntax proposals, and TypeScript lowers them to private fields plus accessors.
  • Static, #private and public forms are all allowed.