The Analogy: The Petrol Station Forecourt
Stand on the forecourt of a petrol station and watch a single pump. The little screen on it shows an amount to pay, and it climbs as the fuel flows, but that figure is nowhere stored: a meter multiplies the litres delivered by the price per litre and shows the result the instant you look. You read it like a plain number, yet something is computing it live behind the glass. That live-computed reading, exposed as if it were an ordinary value, is a getter: a member you access like a field, but which runs code to produce its answer from the state underneath.
Now watch the attendant change that pump's price. They do not scrawl a new number on the glass; they key it into a keypad, and the keypad clamps it to a sensible range, updates the display, and writes the change into the log. Setting the price is not a raw poke at a stored figure, it is an action with checks and side steps wrapped around it. That is a setter: an assignment that looks like writing a field but runs validation and bookkeeping every time. A reading you can only look at, with no keypad to change it, is a getter with no setter -- exactly a derived value like the amount-to-pay, which you may read but never set directly.
Some things on the forecourt belong to no single pump. The tall price sign at the entrance, the running total of litres the whole site has sold today, the regulator's posted maximum price for the site: these belong to the station itself, not to pump three or pump seven. A static member is the same, data and behaviour that live on the class rather than on any one object. The kiosk that only brings a pump into service after it passes a calibration check is a static factory guarding creation, the day's litre total is a static counter shared by every pump, and the posted maximum price is a static constant fixed once for the whole site.
The failure mode is a gauge that does real work every time it is glanced at, and confusing the site's shared total with a single pump's reading. Imagine a display so badly wired that merely looking at it dispenses a splash of fuel: every glance, including an inspector's idle double-check, pumps a little more, so the reading can never be trusted and the tank drains from being watched. That is a getter with a side effect, firing on every read a debugger or a log makes. The other failure is reading the forecourt's whole-day litre total as though it were one customer's pump reading and billing them for the entire site, which is mistaking a static member for an instance one; they live in different places and stand for different things.
Syntax or Core Structure
A getter exposes a computed value behind plain property syntax, and a setter runs validation on assignment. A getter with no matching setter is a read-only, derived view of the state.
// src/temp.ts
class Temperature {
private c = 0;
get celsius(): number {
return this.c;
}
set celsius(value: number) {
if (value < -273) {
throw new RangeError("below absolute zero");
}
this.c = value;
}
get fahrenheit(): number {
return this.c * 9 / 5 + 32;
}
}
const t = new Temperature();
t.celsius = 20; // calls the setter
console.log(t.celsius); // calls the getter
console.log(t.fahrenheit); // a derived, read-only view
// t.fahrenheit = 100; // refused: fahrenheit has no setter
Output:
20
68
Writing t.celsius = 20 looks like a field assignment but runs the setter, which checks the value before storing it in the private c. Reading t.celsius runs the getter and returns 20. fahrenheit is a getter with no setter: it computes 20 * 9 / 5 + 32, which is 36 + 32, which is 68, fresh on each read. The commented assignment to fahrenheit would be refused, because a getter without a setter is read-only.
Technical Depth: Asymmetric Accessors, Static Members, and Static Reach
A setter may accept a wider type than its getter returns, static members live on the class and pair with a private constructor to guard creation, and this in a static member means the class, not an instance.
A setter can be wider than its getter
Since TypeScript 4.3 a setter may accept more types than the getter returns. This suits a forgiving input that normalises to one strict internal shape.
// src/duration.ts
class Duration {
private ms = 0;
get value(): number {
return this.ms;
}
set value(input: number | string) {
this.ms = typeof input === "string" ? Number.parseInt(input, 10) : input;
}
}
const d = new Duration();
d.value = "500";
console.log(d.value);
d.value = 250;
console.log(d.value);
Output:
500
250
The setter accepts a number or a string, so d.value = "500" and d.value = 250 are both allowed; the string is parsed to 500 and the number stored as is. The getter always returns a number, so d.value reads back 500 then 250. The two sides differ on purpose: the input is generous, the stored state is strict, and callers reading the value never have to handle a string.
Static members belong to the class
A static field, method, or getter lives on the class itself, reached through the class name. Pairing a private constructor with a static factory forces every object through one validating door, and a private static counter can track how many were built.
// src/user.ts
class User {
private static count = 0;
static readonly MAX_NAME = 10;
private constructor(public readonly name: string) {}
static create(name: string): User | null {
if (name.length === 0 || name.length > User.MAX_NAME) {
return null;
}
User.count += 1;
return new User(name);
}
static get total(): number {
return User.count;
}
}
const a = User.create("ada");
const b = User.create("grace");
const c = User.create(""); // rejected: empty name
console.log(a === null);
console.log(c === null);
console.log(User.total);
Output:
false
true
2
create is the only way to build a User, because the constructor is private, and it checks the name against the static MAX_NAME constant. Building "ada" and "grace" succeeds and raises the private static count to 2; create("") is rejected and returns null without touching the count. So a === null is false, c === null is true, and User.total, a static getter reading the shared counter, is 2. A static {} initialisation block, not shown here, runs once when the class is first defined, for one-time setup.
this in a static member is the class
Inside a static member, this refers to the class, and the member cannot see any instance's fields or a class type parameter, because no instance exists at that point.
// src/counter.ts
class Counter {
private static made = 0;
constructor() {
Counter.made += 1;
}
static get made_so_far(): number {
return Counter.made;
}
}
new Counter();
new Counter();
new Counter();
console.log(Counter.made_so_far);
Output:
3
Each new Counter() runs the instance constructor, which reaches the class through Counter.made and raises the shared count. After three constructions the static getter made_so_far returns 3. The counter lives on the class, not on any one instance, which is why every construction adds to the same figure and the total is read through the class name rather than through an object.
Instance against static
| Aspect | Instance member | Static member |
|---|---|---|
| lives on | each object | the class itself |
| accessed as | obj.thing | ClassName.thing |
| this refers to | the instance | the class |
| can use the class type parameter | yes | no |
| typical use | one object's state | constants, factories, counters |
Instance members hold and act on the state of one object; static members hold what belongs to the type as a whole, such as constants, factories, and shared counters.
Real World Example: A Validated Money Type
Money must never be a floating-point number, or invoices round wrong. This Money type stores an integer number of pence, hides its constructor behind static factories that guarantee the integer, exposes the pounds value and a formatted string as getters, and adds only within one currency. An invoice sums several line items through it.
// src/money.ts
class Money {
private constructor(
private readonly pence: number,
public readonly currency: string,
) {}
static fromPence(pence: number, currency: string): Money {
if (!Number.isInteger(pence)) {
throw new TypeError("pence must be an integer");
}
return new Money(pence, currency);
}
static fromPounds(pounds: number, pence: number, currency: string): Money {
return Money.fromPence(pounds * 100 + pence, currency);
}
get pounds(): number {
return Math.floor(this.pence / 100);
}
get formatted(): string {
const rem = this.pence % 100;
const pp = rem < 10 ? "0" + rem : String(rem);
return this.currency + " " + this.pounds + "." + pp;
}
plus(other: Money): Money {
if (other.currency !== this.currency) {
throw new Error("currency mismatch");
}
return Money.fromPence(this.pence + other.pence, this.currency);
}
}
interface Item {
label: string;
amount: Money;
}
function pad(text: string, width: number): string {
return text.padEnd(width);
}
const items: Item[] = [
{ label: "pipe", amount: Money.fromPounds(12, 50, "GBP") },
{ label: "elbow", amount: Money.fromPounds(3, 25, "GBP") },
{ label: "flux", amount: Money.fromPence(199, "GBP") },
];
let total = Money.fromPence(0, "GBP");
const rows: string[] = [];
for (const it of items) {
total = total.plus(it.amount);
rows.push(pad(it.label, 8) + it.amount.formatted);
}
const report = [
"items: " + items.length,
pad("ITEM", 8) + "AMOUNT",
...rows,
"total: " + total.formatted,
];
console.log(report.join("\n"));
Output:
items: 3
ITEM AMOUNT
pipe GBP 12.50
elbow GBP 3.25
flux GBP 1.99
total: GBP 17.74
The constructor is private, so the only way to build a Money is through fromPence, which insists on an integer, or fromPounds, which converts to pence first. That means no Money anywhere in the program can hold a fractional penny. pounds and formatted are getters that derive their answers on demand rather than storing them, and plus refuses to add across currencies, so a running total stays sound.
Trace the pence through each factory. The pipe is 12 * 100 + 50, which is 1250 pence, formatted as "GBP 12.50". The elbow is 3 * 100 + 25, which is 325 pence, formatted as "GBP 3.25". The flux is 199 pence directly, formatted as "GBP 1.99" because Math.floor(199 / 100) is 1 and 199 % 100 is 99. The total accumulates 1250 + 325 + 199, which is 1774 pence, and 1774 formats as 17 pounds and 74 pence, so the footer reads "GBP 17.74".
The design has real limits worth naming. The sharpest flaw is baked into formatted: it assumes every currency has exactly two minor digits, so a zero-decimal currency such as yen would print a spurious decimal point and two invented digits, and a three-decimal currency would be silently truncated. Formatting per currency needs a table of minor-unit counts the type does not carry. The second limit is that currency is a bare string, so Money.fromPence(100, "gpb") builds happily with a typo that only surfaces when plus compares it against "GBP" and throws; a literal union of allowed codes would catch the typo at compile time. The integer-pence core is sound, but the type trusts its currency string and its two-digit assumption further than it should.
Common Mistakes
- Doing expensive work in a getter. Callers assume reading a property is cheap, so a getter that hits the network or loops a large collection surprises them. Make costly work a method named for the computation, or cache the result.
- Giving a getter a side effect. A getter that advances a cursor or dispenses a resource fires on every read, including a debugger hover or a log line, so it can never be read safely. Keep getters pure.
- Naming the backing field the same as the accessor. A
get value()that returnsthis.valuecalls itself forever and overflows the stack. Use a distinct backing field such as a leading-underscore name or a#field.
- Storing what you could derive. Keeping a
fahrenheitfield alongsidecelsiuslets the two drift out of step. Expose the derived value as a getter so it is always computed from the single source of truth.
- Reaching for the class type parameter in a static member. A static member runs with no instance, so a generic class's
Tis not in scope there; only instance members can use it.
- Using static mutable state as a hidden singleton. A mutable static field is shared across every importer, invisible in signatures, and a nightmare to isolate in tests. Prefer passing an instance in.
- Assuming spread or Object.keys copies accessors. Spreading an object evaluates each getter into a plain value and drops the setter entirely, so the copy is a snapshot, not a live view.
- Skipping the setter's validation by writing the backing field directly. Code inside the class can bypass its own setter by assigning the private field, quietly defeating the check. Route internal writes through the setter too when the validation matters.
- Trusting a bare string where a literal union belongs. A field like
currencytyped asstringaccepts any typo; a union of the allowed codes turns the mistake into a compile error instead of a runtime throw.
Best Practices
- Expose derived state as a getter. Compute anything that follows from the stored state rather than storing it separately, so there is one source of truth and nothing to keep in sync.
- Keep getters pure, cheap, and total. A getter should not throw, perform input or output, or mutate anything, because callers treat reading it as a free, safe operation.
- Validate in the setter or use a named method. Put the check in the setter when assignment syntax reads well, or skip the setter for an intention-named method like
applyDiscountwhen the operation deserves a verb.
- Use a distinct backing field. Back an accessor with a differently named private field, such as an underscore or
#name, so the getter never calls itself into a stack overflow.
- Guard invariants with a private constructor and static factories. When a type has rules, hide the constructor and expose validating factories, so an invalid instance cannot exist anywhere in the program.
- Use static readonly for constants that belong to the type. Prefer a
static readonlyon the class over a loose module-level constant when the value is conceptually part of the type.
- Avoid static mutable state as a global store. Reserve static members for constants, factories, and counters that genuinely belong to the type, and pass instances in rather than hiding shared state on the class.
- Prefer literal unions over bare strings for coded fields. Type a currency or a status as a union of its allowed values so the compiler rejects a typo instead of letting it surface at runtime.
Practice Exercises
- The dashboard. Write a
Rectangleclass whosewidthandheightsetters reject non-positive values and which exposes read-onlyareaandperimetergetters, then show that setting a valid width updatesareawhile a zero width throws.
- The forecourt board. Add a private static counter to
Rectanglethat rises on each construction, expose it through astatic get count(), and show that building three rectangles reports a count of three.
- The guarded factory. Build a
Codeclass with a private constructor and astatic parse(input): Code | nullthat accepts only a four-character string, and show that an invalid input returnsnullrather than a bad instance.
- The two-digit trap. Show that the lesson's
Money.formattedprints a wrong result for a zero-decimal currency, then add a static table of minor-unit counts per currency and use it so the formatting is correct for both two-digit and zero-digit currencies.