Script Valley
TypeScript: Complete Course from Zero
Classes and Object-Oriented TypeScriptLesson 5.4

Getters and setters in TypeScript classes

get accessor, set accessor, computed properties, validation in setters, backing fields, accessor vs method

Getters and setters

Accessors look like properties to the caller but run code on get/set:

class Temperature {
  private _celsius: number;

  constructor(celsius: number) {
    this._celsius = celsius;
  }

  get celsius(): number {
    return this._celsius;
  }

  set celsius(value: number) {
    if (value < -273.15) throw new Error("Below absolute zero");
    this._celsius = value;
  }

  get fahrenheit(): number {
    return this._celsius * 9/5 + 32;
  }
}

const t = new Temperature(100);
console.log(t.fahrenheit); // 212 — no () needed
t.celsius = -300;          // throws

When to use accessors

Use a getter when you want a computed read-only value to look like a property. Use a setter when you need validation, transformation, or side effects on write. Do not add getters/setters just to wrap every private field — it adds noise without benefit if there is no logic involved.

Up next

TypeScript decorators introduction class and method decorators

Sign in to track progress