Classes

suggest change

Modern classes support field declarations, parameter properties, accessors, abstract, override, and ECMAScript #private fields.

abstract class Account {
  #balance = 0;

  protected constructor(readonly owner: string) {}

  deposit(amount: number): void {
    if (amount <= 0) throw new RangeError("amount must be positive");
    this.#balance += amount;
  }

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

  abstract describe(): string;
}

class SavingsAccount extends Account {
  constructor(owner: string, readonly rate: number) {
    super(owner);
  }

  override describe(): string {
    const annualInterest = this.balance * this.rate;
    return `${this.owner}: ${this.balance} (${annualInterest} annual interest)`;
  }
}

const account = new SavingsAccount("Ada", 0.04);
account.deposit(100);
console.log(account.describe());

The private keyword is enforced by TypeScript, whereas #balance is private at runtime as well. Prefer composition when inheritance does not model a genuine substitutable relationship.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents