TS Getters / Setters
Getters and setters look like fields from outside, but run code on access. TypeScript types them just like methods.
Basics
TS
class Temperature {
private _celsius = 0;
get celsius(): number { return this._celsius; }
set celsius(v: number) {
if (v < -273.15) throw new RangeError('below absolute zero');
this._celsius = v;
}
get fahrenheit(): number {
return this._celsius * 9 / 5 + 32;
}
}
const t = new Temperature();
t.celsius = 25;
console.log(t.celsius, t.fahrenheit); // 25 77
Read-only via getter only
TS
class Account {
constructor(private _balance: number) {}
get balance(): number { return this._balance; }
}
const a = new Account(100);
// a.balance = 200; // ✗ error — no setter
Different types on get / set (4.3+)
TS
class Box {
private _v = '';
get value(): string { return this._v; }
set value(v: string | number) {
this._v = String(v);
}
}
const b = new Box();
b.value = 42; // OK — setter accepts number
b.value = 'hi'; // OK
Static getters
TS
class Config {
private static _env = process.env;
static get isProd(): boolean { return Config._env.NODE_ENV === 'production'; }
}
vs plain methods
| Pick a getter | Pick a method |
|---|---|
| Looks like a field, never throws, fast. | Might take time, throw, or take args. |
| Pure read of derived state. | Does work — fetches, computes, calls. |
| Code consumers expect to use like a property. | Verb-shaped operations. |
Tip: Don't put expensive work inside a getter. Calling code expects field access — slow getters surprise everyone.
Example
Example
class Temperature {
private _c = 0;
get celsius() { return this._c; }
set celsius(v) { this._c = v; }
get fahrenheit() { return this._c * 9/5 + 32; }
}
const t = new Temperature();
t.celsius = 25;
console.log(t.celsius, t.fahrenheit);
Try it Yourself »
Exercise
Define a getter for "celsius".
celsius() { return this._c; }
Three letters.
Discussion
Loading…