Access modifiers
Overview
A class is more than a bag of properties: its methods keep its data valid. A bank account’s balance should only change through deposit and withdraw, which check the amounts. Access modifiers let you say which members are part of the public API and which are internal, so the type checker stops other code from reaching around the rules.
public
Members are public by default; writing public is optional and mostly used for emphasis:
class Greeter {
public greet(name: string) {
return `Hello, ${name}`;
}
}private
A private member can only be used inside the class body:
class BankAccount {
private balance = 0;
deposit(amount: number) {
if (amount <= 0) throw new RangeError("Deposit must be positive");
this.balance += amount; // ✓ inside the class
}
}
const acc = new BankAccount();
acc.balance = 1_000_000;
// error TS2341: Property 'balance' is private and only accessible within class 'BankAccount'.protected
A protected member is visible inside the class and its subclasses, but not outside:
class Shape {
protected describeSize(size: number): string {
return size > 100 ? "large" : "small";
}
}
class Square extends Shape {
side = 12;
describe() {
return `a ${this.describeSize(this.side ** 2)} square`; // ✓ subclass
}
}
new Square().describeSize(4);
// error TS2445: Property 'describeSize' is protected and only accessible within class 'Shape' and its subclasses.Use protected for helpers that subclasses need but outside code shouldn’t call.
Compile time vs run time
Here’s the catch: private and protected are TypeScript features. They’re checked, then erased like all types. In the JavaScript output, balance is an ordinary property, and anyone can reach it:
(acc as any).balance = 1_000_000; // compiles (any switches off checking) and works at run time
console.log(acc); // BankAccount { balance: 1000000 } — and it shows up in logsFor most application code, that’s fine: the type checker stops accidental misuse, which is what you want. When data must be truly hidden — security-sensitive values, library internals — use JavaScript’s own private fields.
#private fields
Names starting with # are private at run time, enforced by the JavaScript engine itself:
class BankAccount {
#balance = 0;
deposit(amount: number) {
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.#balance;
// error TS18013: Property '#balance' is not accessible outside class 'BankAccount' because it has a private identifier.Even at run time, #balance can’t be read from outside, doesn’t appear in Object.keys, and isn’t printed by most loggers. Subclasses can’t see it either — there’s no #protected.
private x |
#x |
|
|---|---|---|
| Checked by TypeScript | yes | yes |
| Hidden at run time | no | yes |
| Visible in subclasses | no | no |
Escape with as any |
yes | no |
| Works with type stripping | yes | yes |
Many teams now default to # for genuinely private state and use private mostly for methods. Either is fine; be consistent.
readonly
readonly stops a field from being reassigned after the constructor finishes:
class Order {
readonly id: string;
readonly createdAt = new Date();
constructor(id: string) {
this.id = id; // ✓ allowed in the constructor
}
rename() {
this.id = "new";
// error TS2540: Cannot assign to 'id' because it is a read-only property.
}
}Combine it with visibility: private readonly cache = new Map() — the reference never changes, though the Map’s contents can.
Getters for read-only views
A common pattern: keep the data private, expose a getter. Outside code can read the value but only change it through methods that enforce the rules:
class Counter {
#count = 0;
get count() { return this.#count; }
increment() { this.#count++; }
}
const c = new Counter();
c.count; // ✓ read
c.count = 5;
// error TS2540: Cannot assign to 'count' because it is a read-only property.Designing the public surface
- Start with everything private (or
#), and make members public only when outside code needs them. - Expose operations (
deposit,withdraw), not raw data that must stay consistent. - Return copies of internal arrays and objects (
[...this.history]) so callers can’t modify them behind your back. - Use
protectedsparingly — every protected member is part of the contract with subclasses.
Remember:
publicfor the API,protectedfor subclasses,privatefor internals (checked at compile time),#privatewhen it must be hidden at run time too, andreadonlyfor values set once.
A protected bank account
Write class BankAccount with: a readonly id (string); a JavaScript private field #balance (number, starting at 0); a protected method record(entry: string) that adds to a private history array; public methods deposit(amount) and withdraw(amount) (throw a RangeError for non-positive amounts or insufficient funds) that both call record; a public getter balance; and a public statement(): string[] returning a copy of the history. Then write SavingsAccount extends BankAccount with a readonly rate and an addInterest() method that deposits interest and calls the protected record. Exercise them and print the balance and statement. Show with // @ts-expect-error that outside code can’t call record, can’t write balance, and can’t reassign id.
class BankAccount {
// readonly id, #balance, private history, protected record(),
// deposit(), withdraw(), get balance(), statement()
}
class SavingsAccount extends BankAccount {
// readonly rate, addInterest()
}class BankAccount {
readonly id: string;
#balance = 0;
private history: string[] = [];
constructor(id: string) {
this.id = id;
}
protected record(entry: string): void {
this.history.push(entry);
}
deposit(amount: number): void {
if (amount <= 0) throw new RangeError("Deposit must be positive");
this.#balance += amount;
this.record(`+${amount.toFixed(2)}`);
}
withdraw(amount: number): void {
if (amount <= 0) throw new RangeError("Withdrawal must be positive");
if (amount > this.#balance) throw new RangeError("Insufficient funds");
this.#balance -= amount;
this.record(`-${amount.toFixed(2)}`);
}
get balance(): number {
return this.#balance;
}
statement(): string[] {
return [...this.history];
}
}
class SavingsAccount extends BankAccount {
readonly rate: number;
constructor(id: string, rate: number) {
super(id);
this.rate = rate;
}
addInterest(): void {
const interest = Math.round(this.balance * this.rate * 100) / 100;
this.deposit(interest);
this.record(`interest at ${this.rate * 100}%`); // protected: allowed in a subclass
}
}
const savings = new SavingsAccount("SAV-1", 0.05);
savings.deposit(200);
savings.withdraw(50);
savings.addInterest();
try {
savings.withdraw(1000);
} catch (error) {
console.log(error instanceof RangeError ? error.message : error); // Insufficient funds
}
console.log(savings.balance); // 157.5
console.log(savings.statement().join(" | ")); // +200.00 | -50.00 | +7.50 | interest at 5%
// Misuse that TypeScript rejects (never called, so it never runs):
function misuse(account: SavingsAccount) {
// @ts-expect-error -- record is protected
account.record("hack");
// @ts-expect-error -- balance has a getter but no setter
account.balance = 1_000_000;
// @ts-expect-error -- id is readonly
account.id = "SAV-2";
}Summary
public(the default) members are usable anywhere;protectedones inside the class and its subclasses;privateones only inside the class.- TypeScript’s
privateandprotectedare compile-time checks — the properties still exist at run time. - JavaScript
#privatefields are truly hidden at run time, and TypeScript types them too. readonlystops reassignment after the constructor; combine it with any visibility.- Keep the public surface small: expose methods that keep the object valid, hide the data they protect.