Static Members

Belonging to the Class

static members belong to the class itself, not to each object. Use them for counters, constants and factory methods.

Example

class Order {
  static readonly GST_RATE = 0.18;
  private static nextId = 1000;

  readonly id: string;

  private constructor(public amount: number) {
    this.id = "OD-" + Order.nextId++;
  }

  static create(amount: number): Order {
    if (amount <= 0) throw new Error("Amount must be positive");
    return new Order(amount);
  }

  get totalWithGst(): number {
    return Math.round(this.amount * (1 + Order.GST_RATE));
  }
}

const a = Order.create(1000);
const b = Order.create(250);
console.log(a.id, a.totalWithGst);
console.log(b.id, b.totalWithGst);
console.log("GST:", Order.GST_RATE);

Output

OD-1000 1180
OD-1001 295
GST: 0.18

Private Constructor

Note: A private constructor forces callers to use the static factory (Order.create), so validation can never be skipped. new Order(5) from outside is a compile error. The same trick implements the singleton pattern.