TypeScript Lesson 8: Classes & OOP

📘 TypeScript CourseLesson 8 of 12 · 67% complete

TypeScript supercharges JavaScript classes with access modifiers, abstract classes, and interface implementation — making OOP clean and safe.

Access Modifiers

class BankAccount {
  // public: accessible from anywhere (default)
  public owner: string;
  
  // private: only inside THIS class
  private balance: number;
  
  // protected: this class + subclasses
  protected accountNumber: string;
  
  // readonly: set once, never changed
  readonly createdAt: Date = new Date();
  
  constructor(owner: string, initialBalance: number) {
    this.owner = owner;
    this.balance = initialBalance;
    this.accountNumber = Math.random().toString(36).slice(2);
  }
  
  deposit(amount: number): void {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.balance += amount;
  }
  
  get currentBalance(): number { return this.balance; } // getter
}

Implements Interface

interface Serializable {
  serialize(): string;
  deserialize(data: string): void;
}

interface Printable {
  print(): void;
}

// Class can implement multiple interfaces
class Document implements Serializable, Printable {
  constructor(private content: string) {}
  
  serialize(): string { return JSON.stringify({ content: this.content }); }
  deserialize(data: string): void { this.content = JSON.parse(data).content; }
  print(): void { console.log(this.content); }
}

Abstract Classes

abstract class Shape {
  abstract area(): number;       // subclass MUST implement
  abstract perimeter(): number;  // subclass MUST implement
  
  // Shared method available to all subclasses
  describe(): string {
    return `Area: ${this.area().toFixed(2)}, Perimeter: ${this.perimeter().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) { super(); }
  area() { return Math.PI * this.radius ** 2; }
  perimeter() { return 2 * Math.PI * this.radius; }
}

new Shape(); // ❌ Error — cannot instantiate abstract class
new Circle(5).describe(); // ✅ OK

🏋️ Practice Task

Build a game character system. Abstract class Character has: name, hp, maxHp, abstract attack() and defend() methods, shared methods: heal(amount), isDead() → boolean, status() → string. Subclasses: Warrior (high HP/defense), Mage (powerful attack, low HP). Test in a battle simulation.

💡 Hint: constructor(protected name: string, protected hp: number, protected maxHp: number) {}. heal: this.hp = Math.min(this.maxHp, this.hp + amount)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *