TypeScript theorytheory 0/50 · 0%
Foundations · easy

12. Access modifiers & readonly

public, private, protected, and immutable fields.

Access modifiers control visibility of class members: `public` (default, accessible anywhere), `private` (only within the declaring class), and `protected` (the class and its subclasses).

ts
class Account {
  private secretKey: string;
  protected balance: number = 0;
  public readonly id: string;

  constructor(id: string, secretKey: string) {
    this.id = id;
    this.secretKey = secretKey;
  }
}

class Multisig extends Account {
  addSigner() {
    this.balance += 0; // OK: protected is visible to subclasses
    // this.secretKey; // error: private is not
  }
}

`readonly` fields can be set once (in the declaration or constructor) and never reassigned after. Unlike `private`/`protected`, which are purely compile-time (erased at runtime), true runtime privacy uses the `#field` JavaScript private-field syntax.

Check your understanding

  1. 1. Which modifier allows access from subclasses but not from outside code?

  2. 2. Are `private` fields hidden at runtime in compiled JS?

  3. 3. When can a `readonly` field be assigned?