Lesson 13 of 20

Classes in TypeScript

Class Basics & Access Modifiers

TypeScript enhances JavaScript classes with access modifiers (public, private, protected) and type annotations.

Example
class User {
  public name: string;      // accessible anywhere
  private email: string;    // only within this class
  protected age: number;    // this class and subclasses

  constructor(name: string, email: string, age: number) {
    this.name = name;
    this.email = email;
    this.age = age;
  }

  // Shorthand: parameter properties
}

// Shorthand version — declares and assigns in constructor
class Product {
  constructor(
    public name: string,
    public price: number,
    private sku: string
  ) {}
}

Implementing Interfaces

Classes can implement interfaces to guarantee they follow a specific contract.

Example
interface Printable {
  print(): string;
}

interface Loggable {
  log(): void;
}

class Invoice implements Printable, Loggable {
  constructor(public client: string, public amount: number) {}

  print(): string {
    return `Invoice: ${this.client} - $${this.amount}`;
  }

  log(): void {
    console.log(this.print());
  }
}

const inv = new Invoice("Acme", 500);
inv.log(); // "Invoice: Acme - $500"

Abstract Classes

Abstract classes cannot be instantiated directly. They define a base structure that subclasses must implement.

Example
abstract class Shape {
  abstract area(): number;
  abstract perimeter(): number;

  describe(): string {
    return `Area: ${this.area()}, Perimeter: ${this.perimeter()}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }

  perimeter(): number {
    return 2 * Math.PI * this.radius;
  }
}

const c = new Circle(5);
console.log(c.describe());