Classes

TypeScript enhances JavaScript classes with type annotations and access modifiers.

Basic Class

class Person {
  name: string
  age: number

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

  greet(): string {
    return \`Hi, I'm \${this.name}\`
  }
}

const alice = new Person('Alice', 25)
console.log(alice.greet())

Access Modifiers

class BankAccount {
  public owner: string          // accessible everywhere
  private balance: number       // only within class
  protected currency: string    // class and subclasses
  readonly id: string           // cannot be changed after init

  constructor(owner: string, initial: number) {
    this.owner = owner
    this.balance = initial
    this.currency = 'USD'
    this.id = Math.random().toString(36).slice(2)
  }

  deposit(amount: number): void {
    this.balance += amount
  }

  getBalance(): number {
    return this.balance
  }
}

Implements Interface

interface Printable {
  print(): void
}

class Report implements Printable {
  title: string

  constructor(title: string) {
    this.title = title
  }

  print(): void {
    console.log(\`Printing: \${this.title}\`)
  }
}