Skip to content

Classes#

Basic Class#

class Person {
  constructor(public name: string, public age: number) {}
}

Access Modifiers (public, private, protected)#

class Car {
  private engineCode: string; // Only accessible inside Car
  protected model: string;    // Accessible in Car and subclasses
  public brand: string;       // Accessible everywhere
}

Readonly Properties#

class Config {
  readonly apiUrl: string = "http://api.com";
}

Getters and Setters#

class User {
  private _age: number = 0;

  get age() { return this._age; }
  set age(v: number) { this._age = v; }
}

Static Members#

class MathUtil {
  static PI = 3.14;
  static area(r: number) { return this.PI * r * r; }
}

Inheritance#

class Dog extends Animal {
  bark() { console.log('Woof'); }
}

Abstract Class#

abstract class Shape {
  abstract area(): number; // Must be implemented by subclass
}

Implements Interface#

class Log implements Logger {
  log(msg: string) { console.log(msg); }
}

Generic Class#

class Box<T> {
  content: T;
  constructor(v: T) { this.content = v; }
}

Singleton Pattern#

class DB {
  private static instance: DB;
  private constructor() {} // Private constructor

  static get(): DB {
    if (!this.instance) this.instance = new DB();
    return this.instance;
  }
}