Sub topic 8
`private`: Hiding Implementation Details
Assume you know basic TypeScript types, JavaScript classes, and the this keyword. In TypeScript, private marks a class member as accessible only inside the class that declares it. It protects the class's internal state from accidental use by callers.
Why use `private`?
A class should expose the operations that callers need while hiding the details that must remain consistent. This separation is called encapsulation. A private field can store state, while public methods control how that state changes.
class Account {
public readonly id: string;
private balance: number;
constructor(id: string, initialBalance: number) {
this.id = id;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new Account("a-1", 100);
account.deposit(50);
console.log(account.getBalance()); // 150
// account.balance = 0;
// Error: Property 'balance' is private and only accessible within class 'Account'.
// account.id = "x";
// Error: Cannot assign to 'id' because it is a read-only property.The caller does not edit balance directly. The deposit method validates the amount before changing it. This gives the class one place to enforce its rules.
A private member can be a field, method, accessor, or constructor. Private methods are useful for helper logic that is not part of the class's public API.
class Order {
private status: "new" | "paid" = "new";
pay(): void {
this.requireNew();
this.status = "paid";
}
getStatus(): string {
return this.status;
}
private requireNew(): void {
if (this.status !== "new") {
throw new Error("The order has already been paid");
}
}
}
const order = new Order();
order.pay();
console.log(order.getStatus()); // paidCompile-time privacy
TypeScript checks private during type checking. Code outside the class cannot access the member, and subclasses cannot access it either. A subclass must use a public or protected method instead.
flowchart TD
Caller["Code using the class"] --> Public["Public methods"]
Public --> Private["Private state and helpers"]
Subclass["Subclass"] --> Public
Caller -. "blocked by TypeScript" .-> Private
Subclass -. "also blocked" .-> PrivatePrivate members also affect type compatibility. Two classes with identical public methods are often compatible by structure. If each class declares a private member, TypeScript treats those private members as belonging to different declarations, so the classes are not interchangeable.
Exercise
Why should Account expose deposit instead of making balance public?
Show answer
deposit can validate amounts and preserve the account's rules, while a public balance could be changed to an invalid value directly.