private: Class-Internal Members
What you'll learn: How to restrict access to properties and methods so they can only be used inside the class that defines them.
Why private Matters
Think of a class like a house with both public rooms (living room, kitchen) and private rooms (bedroom, bathroom). The private keyword lets you mark certain properties and methods as "bedroom-level privacy"—only the class itself can access them, not external code or even subclasses.
By default, everything in a TypeScript class is public. The private modifier changes that, creating a boundary that the compiler enforces.
Basic private Syntax
class BankAccount {
public accountNumber: string;
private balance: number;
constructor(accountNumber: string, initialBalance: number) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public deposit(amount: number): void {
this.balance += amount; // ✓ OK: private members accessible within class
}
public getBalance(): number {
return this.balance; // ✓ OK: internal access
}
}
const account = new BankAccount("12345", 1000);
console.log(account.accountNumber); // ✓ OK: public property
console.log(account.balance); // ✗ Error: Property 'balance' is private
The balance property can only be read or modified by methods inside the BankAccount class. External code has no direct access.
private Methods
You can also make methods private:
class PasswordValidator {
private hashPassword(password: string): string {
return "hashed_" + password; // Simplified example
}
public savePassword(password: string): void {
const hashed = this.hashPassword(password); // ✓ OK: internal call
// Save hashed to database...
}
}
const validator = new PasswordValidator();
validator.savePassword("secret123"); // ✓ OK
validator.hashPassword("test"); // ✗ Error: Method 'hashPassword' is private
Compile-Time Only
TypeScript's private is a compile-time safety feature. The JavaScript output still has all properties accessible—TypeScript just prevents you from writing code that breaks the privacy contract. This protects you during development and refactoring, but doesn't create true runtime encapsulation.
Key Takeaway: Use private to hide implementation details within a class boundary, preventing external code from depending on internal structure and giving you freedom to refactor internals without breaking external usage.