Menu

Access Modifiers and Encapsulation

Lesson 2: Access Modifiers and Encapsulation

Which modifiers are available?

Modifier Accessible from Enforced at runtime?
public (default) Anywhere –
protected The class and its subclasses No (TypeScript only)
private The class only No (TypeScript only)
#field (JavaScript private) The class only Yes
readonly Read anywhere it is visible; assigned only in the declaration or constructor No

Example

class Wallet {
  #balance = 0; // Truly private at runtime
  private readonly history: { amount: number; at: Date }[] = [];

  constructor(public readonly ownerId: string) {}

  addMoney(amount: number): void {
    if (amount <= 0) throw new Error('Amount must be positive');
    this.#balance += amount;
    this.history.push({ amount, at: new Date() });
  }

  pay(amount: number): boolean {
    if (amount > this.#balance) return false;
    this.#balance -= amount;
    this.history.push({ amount: -amount, at: new Date() });
    return true;
  }

  get balance(): number {
    return this.#balance;
  }
}

const wallet = new Wallet('c7');
wallet.addMoney(50000);
wallet.#balance = 1_000_000;
// Error: Property '#balance' is not accessible outside class 'Wallet'.

How it works

  • Parameter properties (constructor(public readonly ownerId: string)) declare and assign a field in one step.
  • private and protected are checked by TypeScript only, and erased in the output. #private fields are enforced by JavaScript itself.
  • Exposing a getter without a setter makes balance read-only from outside, while the class can still change it.
  • Parameter properties generate JavaScript code, so they are not erasable (Lesson 4).

Common mistakes

Mistake Effect Fix
Relying on private for security Values visible at runtime Use #private or keep secrets on a server
Making every field public Any code can break invariants Expose methods that validate changes
Mixing private and # styles randomly Inconsistent codebase Pick one convention per project

Key takeaways

  • Use private/protected for compile-time encapsulation and #private for runtime privacy.
  • Change state through methods that enforce rules.

Try it: Add a #transactions list to Wallet and a method that returns a read-only copy of it.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details