Sub topic 11
Getters and Setters for Controlled Access
This chapter assumes you know basic TypeScript types, how classes declare fields and methods, and what private and public mean. It covers accessors: getters and setters that look like properties but run code.
What accessors are
An accessor is a member that is read and written like a field, but runs a function underneath. A getter uses the get keyword and runs when code reads the property. A setter uses the set keyword and runs when code assigns to it.
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 t = new Temperature();
t.celsius = 100;
console.log(t.celsius); // 100
console.log(t.fahrenheit); // 212Callers write t.celsius = 100, with no parentheses. The setter checks the value before it reaches the private backing field _celsius. A backing field is the real storage behind an accessor. The leading underscore is a common convention, not a language rule. The backing field needs a different name from the accessor, because two members cannot share one name.
Why use them
- Validation. The setter can reject bad values, so the object never holds an invalid state.
- Computed values.
fahrenheitis derived from_celsius, so it cannot drift out of sync. - Stable API. You can start with a plain public field and later turn it into an accessor. Callers do not change their code.
- Side effects. A setter can notify listeners, update a cache, or log the change.
Read-only and write-only properties
A getter without a setter makes a read-only property. In the example above, fahrenheit has no setter, so this fails to compile:
class Temperature {
private _celsius = 0;
get fahrenheit(): number {
return (this._celsius * 9) / 5 + 32;
}
}
const t = new Temperature();
// t.fahrenheit = 50; // Error: Cannot assign to 'fahrenheit' because it is a read-only property.
console.log(t.fahrenheit); // 32A setter without a getter is allowed, but reading the property returns undefined at runtime. It is rarely a good design.
Rules the compiler enforces
- Accessors require a compile target of ES5 or later. Any modern target works.
- If a property has a getter but no setter, TypeScript treats it as
readonly. - The getter must return a value on every path.
- A getter and setter for the same name must have the same access modifier in older versions of the language. Since TypeScript 5.1, they may have different types for unrelated reads and writes, as described below.
- A setter cannot declare a return type.
You can still apply access modifiers to accessors. A private getter is visible only inside the class, and a protected setter is usable by subclasses.
Different types for reading and writing
Since TypeScript 5.1, a getter and a setter may have unrelated types. Earlier versions required the getter type to be assignable to the setter type. The setter type is what callers may assign, and the getter type is what they read.
class Settings {
private _timeout = 1000;
get timeout(): number {
return this._timeout;
}
set timeout(value: number | string) {
this._timeout = typeof value === "string" ? Number.parseInt(value, 10) : value;
}
}
const s = new Settings();
s.timeout = "2500";
console.log(s.timeout); // 2500Use this sparingly. It helps when a setter accepts convenient input, such as a string from a form field, and the getter always returns a normalized value.
Accessors in a hierarchy
Subclasses inherit accessors and can override them. A subclass that overrides an accessor should keep the same shape, with a getter where the base had one and a setter where the base had one. Overriding only the setter in a subclass leaves the property with no getter, so reads return undefined. Override both together.
class Base {
protected _name = "base";
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
}
class Trimmed extends Base {
override get name(): string {
return super.name;
}
override set name(value: string) {
super.name = value.trim();
}
}
const item = new Trimmed();
item.name = " widget ";
console.log(item.name); // widgetCommon errors
- Same name for the field and the accessor. Writing
set celsius(v) { this.celsius = v; }calls the setter again and recurses until the stack overflows. Assign to the backing field instead. - Expensive getters. Callers assume reading a property is cheap. If a getter does heavy work, make it a method such as
computeReport()so the cost is visible. - Throwing from getters. A getter that throws surprises code that logs or spreads the object. Reserve exceptions for setters and methods.
- Side effects in getters. A getter that changes state makes behavior depend on how often something is read.
- Expecting accessors in
Object.keys. Accessors are defined on the prototype, so they do not appear as own properties.JSON.stringifyskips them too, and you see only the backing field.
class Box {
private _size = 5;
get size(): number {
return this._size;
}
}
const box = new Box();
console.log(Object.keys(box)); // ["_size"]
console.log(JSON.stringify(box)); // {"_size":5}Accessors and `this`
Accessors run with this set to the object that was accessed, like methods. If you copy the getter's result into a variable, you hold a plain value, not a live view. If you destructure, const { fahrenheit } = t, the getter runs once at that moment.
Choosing between accessors and methods
| Situation | Prefer |
|---|---|
| Cheap, validation on assignment | Setter |
| Derived value with no side effects | Getter |
| Costly or asynchronous work | Method |
| Operation with several parameters | Method |
| Value that never changes after construction | `readonly` field |
If no logic is needed, a plain readonly or public field is simpler than an accessor that only forwards to a backing field.
Exercises
Exercise
A class has set age(value: number) { this.age = value; }. What happens when you assign to age, and how do you fix it?
Show answer
The setter assigns to this.age, which calls the same setter again, so it recurses until a stack overflow (RangeError). Store the value in a differently named private field, such as _age, and have the getter and setter use that field.
Exercise
You write a class with get total(): number and no setter. What does the compiler do with order.total = 10, and what does Object.keys(order) show for total?
Show answer
The compiler reports an error because total is read-only. Object.keys(order) does not list total, because the accessor lives on the prototype and not as an own property of the instance.
Exercise
A getter get report() takes two seconds to build a summary from a database. Why should it become a method?
Show answer
Callers expect property reads to be cheap and side-effect free. A method such as buildReport() signals that real work happens, so callers can cache the result and avoid calling it repeatedly.