Lessons in this course (9)

4. Classes, access modifiers and enums

Intermediate★ Must knowLesson 4 of 9
typescript
abstract class Account {
  private static nextId = 1;
  readonly id = Account.nextId++;
  constructor(public owner: string, protected balance = 0) {}   // parameter properties
  deposit(amount: number) { if (amount <= 0) throw new Error("Invalid"); this.balance += amount; }
  abstract monthlyFee(): number;
}
class Savings extends Account implements Printable {
  monthlyFee() { return this.balance > 10_000 ? 0 : 5; }
  print() { return `${this.owner}: ${this.balance}`; }
}
interface Printable { print(): string; }

// enum vs union
enum Role { Admin = "ADMIN", User = "USER" }       // generates runtime JS object
type RoleU = "ADMIN" | "USER";                       // zero runtime cost — usually preferred
  • private (TS-only, compile-time) vs #field (JavaScript private, enforced at runtime).
  • readonly vs const: readonly for properties, const for variables.
  • implements checks a class matches an interface; it doesn't add code.