The Analogy: The Zones of a Working Hospital
A hospital is one building, but nobody walks through it freely. The moment you step past the entrance you are in a zone, and the zone decides which doors will open for you. There is the public foyer where anyone off the street may sit, the staff-only wards behind swing doors that only badged staff pass, and the controlled-drugs cupboard on each ward with a single key on the ward sister's belt. The same three-way split governs a class: every field and method lives in one of these zones, and the modifier on it is the sign on the door.
The public foyer is open to all. Reception, the shop, the waiting hall: a visitor with no badge at all may use any of them, and the hospital advertises them as the way in. A public member is the same. Any code holding the object may read it or call it, and because it is advertised as the way in, callers everywhere come to depend on it. That is the power and the cost of public: it is the hospital's promised entrance, and once promised it cannot quietly move.
Behind the swing doors the rules tighten. The staff-only wards are open to the qualified staff and also to the student doctors on rotation who are learning the trade, but never to a visitor: that is protected, reachable by the class and by any class that extends it, but closed to outside code. The controlled-drugs cupboard is tighter still. Only the ward sister carries its key; not even the students on her ward may open it. That is private, reachable only from inside the very class that declared it, closed even to a subclass. The staff corridor and the drugs cupboard are both shut to the public, but they differ precisely in whether the students who inherit the ward may pass.
The failure mode is trusting the cupboard's lock against someone carrying a master key. The controlled-drugs cupboard has a genuine lock, but the facilities office holds a master key that opens every ordinary lock in the building, and the paper inventory lists what is inside for anyone who reads it. A determined person with the master key, or a glance at the inventory sheet, reaches the "locked" contents anyway. That is exactly what private is: real discipline against honest staff, but erased at runtime, so a cast to any or a look at the serialized object walks straight in. The one door a master key cannot open is the sealed pharmacy safe with its own biometric lock, which is the # private field: genuinely shut to everyone outside, at the cost that even the students can never reach it and the building needs the newer wiring to fit it.
Syntax or Core Structure
Each member carries one modifier. public is the default and opens to everyone, protected opens to the class and its subclasses, and private opens only to the declaring class. A method may freely reach all three on this.
// src/account.ts
class Account {
public readonly id: string;
protected balance: number;
private pin: string;
constructor(id: string, pin: string) {
this.id = id;
this.balance = 0;
this.pin = pin;
}
deposit(amount: number): void {
this.balance += amount;
}
show(): string {
return this.id + ": " + this.balance;
}
}
const a = new Account("acc1", "1234");
a.deposit(50);
a.deposit(20);
console.log(a.show());
// a.balance; // refused: balance is protected
// a.pin; // refused: pin is private
Output:
acc1: 70
The constructor sets the public id, the protected balance to 0, and the private pin. Two deposits raise balance to 50 + 20, which is 70, and show reads both id and balance from inside the class where every zone is reachable, printing "acc1: 70". The two commented lines would fail to compile: outside code may read the public id but not the protected balance or the private pin.
Technical Depth: Reach, the Compile-Time Fiction, and the Real Lock
Protected reaches subclasses where private does not, the private keyword is erased at runtime, and a # field is a genuine runtime lock with a cost.
protected reaches a subclass, private does not
A subclass may touch a protected member of its base but not a private one. This is the difference between the staff corridor, open to the students on rotation, and the drugs cupboard, closed even to them.
// src/ward.ts
class Ward {
protected beds = 0;
private key = "sister";
admit(): void {
this.beds += 1;
}
}
class Annex extends Ward {
report(): string {
this.beds += 2; // allowed: beds is protected
// return this.key; // refused: key is private, closed to a subclass
return "beds " + this.beds;
}
}
const annex = new Annex();
annex.admit();
console.log(annex.report());
Output:
beds 3
beds starts at 0; admit raises it by 1 and report raises it by a further 2, so it prints "beds 3". The subclass reaches beds because it is protected, but the commented this.key line would not compile, because key is private and closed even to a class that extends Ward. Protected is the widening that private refuses.
The private keyword is a compile-time fiction
private is checked by the compiler and then erased. At runtime the field is an ordinary property, reachable through a cast and printed by JSON.stringify, so it is discipline against honest code, not a lock against a determined one.
// src/fiction.ts
class Vault {
private code = "0000";
}
const v = new Vault();
// v.code; // refused at compile time
console.log((v as { code: string }).code);
console.log(JSON.stringify(v));
Output:
0000
{"code":"0000"}
The direct v.code would be refused by the compiler, but casting v to a type that admits code reaches it at runtime and prints "0000", and JSON.stringify serialises it plainly as {"code":"0000"}. The private marking vanished in the emitted JavaScript; it was the master key and the inventory sheet all along. Use private to express design intent, never to keep a secret from code that ignores the types.
A # field is the real lock
A field named with a leading # is genuinely private at runtime. It cannot be reached from outside by any cast, and it is left out of JSON.stringify entirely.
// src/real.ts
class RealVault {
#code = "0000";
check(candidate: string): boolean {
return candidate === this.#code;
}
}
const r = new RealVault();
console.log(r.check("0000"));
console.log(r.check("9999"));
console.log(JSON.stringify(r));
Output:
true
false
{}
The only way to test #code is through the class's own check method: "0000" matches and returns true, "9999" does not and returns false. JSON.stringify cannot see the field at all, so it serialises an empty {}. This is the biometric safe: a real lock no master key opens. The cost is that a # field has no protected equivalent, so a subclass can never reach it, and it needs a compile target of ES2022 or newer to be emitted.
The four zones at a glance
| Modifier | Same class | Subclass | Outside | Survives compilation |
|---|---|---|---|---|
| public (the default) | yes | yes | yes | not applicable |
| protected | yes | yes | no | no |
| private | yes | no | no | no |
| the # field | yes | no | no | yes |
The keyword modifiers are a compile-time discipline that vanishes in the output, while the # field is the only one whose privacy is real at runtime, bought at the price of being closed even to subclasses.
Real World Example: A Cart That Guards Its Own Rule
A shopping cart must keep one rule true at all times: every line holds at least one item, and no code outside the cart may set a quantity directly. The cart holds its lines in a private Map, checks the rule in the one method that adds to it, and hands out only copies of its lines, so the invariant is enforced in a single place rather than trusted everywhere.
// src/cart.ts
interface Line {
sku: string;
qty: number;
}
class Cart {
private items = new Map<string, number>();
add(sku: string, qty: number): void {
if (qty < 1) {
throw new Error("qty must be at least 1");
}
this.items.set(sku, (this.items.get(sku) ?? 0) + qty);
}
lines(): Line[] {
const out: Line[] = [];
for (const [sku, qty] of this.items) {
out.push({ sku, qty });
}
return out;
}
count(): number {
let n = 0;
for (const qty of this.items.values()) {
n += qty;
}
return n;
}
}
function pad(text: string, width: number): string {
return text.padEnd(width);
}
const cart = new Cart();
cart.add("apple", 3);
cart.add("bread", 2);
cart.add("apple", 1);
cart.add("milk", 5);
const rows: string[] = [];
for (const line of cart.lines()) {
rows.push(pad(line.sku, 8) + String(line.qty));
}
const report = [
"skus: " + cart.lines().length + ", items: " + cart.count(),
pad("SKU", 8) + "QTY",
...rows,
];
console.log(report.join("\n"));
Output:
skus: 3, items: 11
SKU QTY
apple 4
bread 2
milk 5
The cart's items map is private, so the only way anything enters it is through add, which rejects a quantity below 1. That is the whole guarantee: because no outside code can reach items, the rule "every quantity is at least one" is enforced by one method rather than trusted at every call site. The lines method builds fresh Line objects rather than returning the map, so a caller who mutates a returned line cannot corrupt the cart's state.
Trace the figures. add("apple", 3) creates the apple entry at 3; add("apple", 1) later finds the existing 3 and sets it to 3 + 1, which is 4, so the two apple calls merge into one line. Bread is 2 and milk is 5. A JavaScript Map preserves insertion order, so the lines print apple, bread, milk in the order their keys were first added. There are 3 distinct skus, and count sums the quantities to 4 + 2 + 5, which is 11, both shown in the header.
The design has real limits worth naming. The sharpest flaw is that the cart can only grow: add is the sole mutator, and it guards the "at least one" rule, but there is no guarded way to reduce or remove a line, so a caller who over-counts has no correct path back and is tempted to reach around the class. A complete design would add a remove and a setQuantity that re-check the invariant. The second limit is that sku is an unvalidated string, so add("", 3) records a line with an empty key that every report then prints; the guard checks the quantity but never the identity. Encapsulation kept the map safe from outside mutation, but a guarded field is only as sound as the checks the class chooses to run inside its own doors.
Common Mistakes
- Treating private as security. The
privatekeyword is erased at runtime, so a cast orJSON.stringifyreaches the field anyway. It is a design tool against honest code, not a lock; a real secret needs a#field or, better, must never reach the client at all.
- Making every member public by default. Every public field and method is a promise callers will depend on and that you can no longer quietly change. Leaving state public also lets any caller mutate it into an invalid combination.
- Forgetting the modifier on a constructor parameter. A bare
constructor(name: string)creates a local, not a field, sothis.nameis never set. A modifier such asprivateorpublicis required for the parameter-property shorthand to declare a field.
- Returning the internal collection from a method.
return this.itemshands the caller a live handle to private state, so they can mutate it behind the class's back. Return a copy or a read-only view instead.
- Reaching for a cast to any in a test to touch a private field. If a test needs to poke at a private member, the design is missing a seam; extract the logic into something testable rather than casting past the modifier.
- Using private on a field a subclass genuinely needs. A member a subclass must reach should be
protected, notprivate; private closes the door even to the classes that extend you.
- Expecting a # field to be reachable from a subclass. A
#field has no protected form, so a subclass cannot see it. When inheritance needs the value, useprotectedand accept that its privacy is compile-time only.
- Assuming a # field works on any compile target. A
#field needs a target of ES2022 or newer to be emitted natively; on an older target it is downlevelled with different semantics. Check the target before relying on it.
- Guarding the quantity but not the identity. A method that validates one argument and waves the rest through, like checking
qtybut accepting anysku, leaves a gap. Validate every argument the invariant depends on.
Best Practices
- Start every member private and promote only when needed. Default to the tightest zone and widen a member to
protectedorpubliconly when a subclass or an outside caller genuinely requires it.
- Pair public with readonly for anything set once. A
public readonly idis the safest field shape: visible to all, changeable by none after construction, so no caller can re-cut an identifier.
- Use parameter properties for stored dependencies. When a constructor's job is to keep its arguments, the modifier shorthand declares and assigns each field in one place and halves the boilerplate.
- Return a copy or a read-only view, never the live collection. Hand callers fresh objects or a
ReadonlyMapso they can read the state without holding a handle that lets them mutate it.
- Reach for # fields when the value must not leak. Use a
#field for anything that must stay out of logs,JSON.stringify, and a debugger's object view, accepting that subclasses cannot reach it.
- Expose intent, not structure. A public
countmethod is a better surface than a publicitemsmap, because it lets the class change how it stores state without breaking callers.
- Enforce each invariant in one method. Keep the state private and funnel every change through methods that re-check the rule, so the guarantee lives in a single place rather than being trusted at every call site.
- Provide guarded paths for every legitimate change. If a value can legitimately go down as well as up, add a guarded method to do so, rather than leaving callers to reach around the class for a correction it never offered.
Practice Exercises
- The locked field. Write a
Thermostatclass with aprivate targetand apublic setTarget(n)that rejects values outside 5 to 30, then show that a valid call updates the target while a direct assignment totargetfails to compile.
- The staff corridor. Write a class
Staffwith aprotected salaryand a subclassManagerthat adds araise(amount)method reachingsalary, then confirm that outside code cannot readsalarydirectly.
- The real lock. Take a class that stores an API key as a
private keyand rewrite it to use a#key, then show the difference by callingJSON.stringifyon an instance of each and observing which one leaks the field.
- The guarded removal. Extend the lesson's
Cartwith aremove(sku)and asetQuantity(sku, qty)that both re-check the "at least one" rule, and show that reducing a line to zero throws rather than leaving an invalid entry.