Sub topic 11
Getters and Setters for Controlled Access
Prerequisites and the basic idea
Assume you know basic TypeScript types, classes, methods, and the this keyword. A getter and a setter are special methods that let a class control property access.
A getter reads a value when code uses property syntax. A setter receives a value when code assigns to that property. Together, they let a class validate or transform data while keeping its internal state private.
class Temperature {
private _celsius = 0;
get celsius(): number {
return this._celsius;
}
set celsius(value: number) {
if (value < -273.15) {
throw new RangeError("Below absolute zero");
}
this._celsius = value;
}
get fahrenheit(): number {
return (this._celsius * 9) / 5 + 32;
}
}
const temperature = new Temperature();
temperature.celsius = 100;
console.log(temperature.celsius); // 100
console.log(temperature.fahrenheit); // 212The private _celsius field stores the state. The getter exposes that state as temperature.celsius. The setter checks the new value before storing it. The computed fahrenheit getter has no setter, so callers can read it but cannot assign to it.
How accessors work
The getter and setter must have the same property name. The getter returns a value. The setter accepts exactly one parameter and normally returns void.
A common mistake is assigning to the accessor from inside itself:
class BrokenTemperature {
private _celsius = 0;
set celsius(value: number) {
// this.celsius = value; // Recursively calls the setter forever
this._celsius = value;
}
}Use a separate backing field such as _celsius. The backing field is an implementation detail. The accessor is the public API.
A getter can also return a copy or a derived value. For example, a class might expose the length of a private array without allowing callers to replace the array. A getter-only property behaves as read-only from outside the class.
Choosing accessors carefully
Use a setter when every assignment must satisfy an invariant, which is a rule that keeps an object valid. For example, a setter can reject a negative balance or normalize a username.
Use a method instead when the action has a meaningful operation or may produce a result, such as deposit(amount) or reset(). A setter should feel like ordinary property assignment, not like an expensive operation or a network request.
> callout note > Getters and setters look like fields to callers, but they execute code. Keep them fast, predictable, and free of surprising side effects.
Exercise
Why does the Temperature class use a private _celsius field instead of assigning to this.celsius inside the setter?
Show answer
Assigning to this.celsius would call the setter again and cause infinite recursion. The separate field stores the value directly.