BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🔐

Access Modifiers: Locking Down Your Class Fields

💡 Use private/protected to control who can see a member and readonly to control whether it can change — combine them to expose the minimum surface a class needs.

In the last card you built a class with constructor and instance fields. By default, every field is public — any code can read or overwrite it. That's often too permissive. TypeScript gives you four keywords to control access: public, private, protected, and readonly.

private means a member is only reachable from inside the same class. protected is one notch looser — it's reachable inside the class and its subclasses, but not from outside. public (the default) is reachable everywhere. Note these are enforced by the compiler, not fully at runtime — TypeScript's private disappears after compilation, unlike JavaScript's true #private fields.

ts
class BankAccount {
  public owner: string;
  private balance: number;      // only BankAccount can touch this
  protected readonly id: string; // subclasses can read; nobody can reassign

  constructor(owner: string, id: string) {
    this.owner = owner;
    this.balance = 0;
    this.id = id;
  }

  deposit(amount: number) { this.balance += amount; }
}

const acc = new BankAccount("Ada", "A-1");
acc.deposit(100);      // ✅ public method mutates private field
acc.balance = 999999;  // ❌ Error: 'balance' is private

readonly is different in kind — it's about mutability, not visibility, so you combine it with the others. A readonly field can be assigned once (in its declaration or the constructor) and never again. It pairs naturally with the parameter-property shorthand: writing constructor(private readonly balance: number) declares the field, marks it private and read-only, and assigns it — all in one line.

🔐 Access Modifiers: Locking Down Your Class Fields — BeCuriouz