TypeScript OOP

Classes & OOP

TypeScript adds real access modifiers, abstract classes, and interface implementation to JavaScript's class syntax, giving you the OOP toolkit of a statically typed language.

TypeScript 5 3 Topics
01

Classes & Access Modifiers

TypeScript adds public, private, and protected modifiers the compiler enforces. Parameter properties declare and assign a field straight from the constructor signature.

TypeScript — Modifiers & Parameter Properties
class Account {
  // parameter properties: declare + assign in one line
  constructor(
    public owner: string,
    private balance: number = 0
  ) {}

  deposit(amount: number): void {
    if (amount <= 0) throw new Error("invalid");
    this.balance += amount;
  }
  getBalance(): number { return this.balance; }
}

const a = new Account("Ada");
a.owner;              // "Ada" — public
// a.balance;         // Error: 'balance' is private
private is enforced by the compiler, not at runtime — it compiles to a normal JS property. For true runtime privacy, use JavaScript's #field syntax, which TypeScript also supports.
02

Abstract Classes & implements

An abstract class is a partial base that can't be instantiated and can declare abstract methods subclasses must fill in. implements makes a class promise to satisfy an interface's shape.

TypeScript — abstract & implements
interface Drawable { draw(): void; }

abstract class Shape implements Drawable {
  abstract area(): number;      // subclass must implement
  draw(): void { console.log("drawing, area:", this.area()); }
}

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

// new Shape();        // Error: cannot instantiate an abstract class
const c = new Circle(2);
c.draw();
implements only checks the shape; it adds no code. extends inherits real implementation. A class can implements many interfaces but extends only one class.
03

Accessors & readonly

TypeScript — get/set & readonly
class Temperature {
  private _celsius = 0;

  get celsius(): number { return this._celsius; }
  set celsius(v: number) {
    if (v < -273.15) throw new Error("below absolute zero");
    this._celsius = v;
  }
  get fahrenheit(): number { return this._celsius * 9 / 5 + 32; }

  static readonly ABSOLUTE_ZERO = -273.15;   // class-level constant
}

const t = new Temperature();
t.celsius = 25;        // runs the setter's validation
t.fahrenheit;         // 77 — computed getter, reads like a field
Getters and setters let a computed or validated value be accessed like a plain property. Pair a private backing field with public accessors to enforce invariants (like the absolute-zero check) without changing how callers use the object.

Quick Quiz

1. TypeScript's private modifier is enforced…
2. constructor(public owner: string) is called a…
3. An abstract class…
4. A class can implements how many interfaces?
5. implements vs extends — implements…