TypeScript Reference ยท Classes, Enums and Decorators
TypeScript getters and setters
Reference for TypeScript get and set accessors: computed properties, validation in setters, read-only getters, and rules for accessor types.
Accessors are methods that look like properties. A get accessor runs when the property is read; a set accessor runs when it is assigned. They let a class expose a computed value or validate input while callers keep using plain property syntax.
A getter without a setter makes a read-only property. Accessors live on the prototype, so they are not listed by Object.keys and they are not copied by object spread.
class Circle { constructor(public radius: number) {} get diameter(): number { return this.radius * 2; } }
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
class C { get name(): T { return ...; } set name(value: U) { ... } static get shared(): T { ... } }
| Rule | Description |
|---|---|
| Getter | Takes no parameters; returns a value. The return type may be inferred. |
| Setter | Takes exactly one parameter and has no return type annotation. |
| Pairing | If only get exists, the property is readonly for the type checker. If only set exists, reading gives undefined at runtime. |
| Types | Since TypeScript 5.1 the getter and setter types may be unrelated. Before that, the getter type had to be assignable to the setter type. |
| Target | Accessors need ES5 or newer. |
Edge cases:
- Both accessors must have the same
staticstatus, and a getter and setter that disagree about accessibility (a public getter with a private setter) are rejected in many compiler versions, so keep the pair consistent and expose a separate method for restricted writes. - A setter without a getter is allowed but rarely useful.
Usage notes
- A getter runs every time it is read. Keep it cheap and free of side effects, or cache the result in a field.
- The backing field needs a different name (
_celsius, or better#celsius). Using the accessor's own name inside it causes infinite recursion. - Accessors are inherited and can be overridden. Override both halves together; overriding only one hides the other.
- Use an accessor when you need validation or a derived value. For plain storage a public field is simpler and faster to read.
- The
accessorkeyword generates a private slot with a getter and setter for you; see accessor.