Lesson 15 +10 XP

Generic Classes

Generic Classes

Classes can take type parameters to handle typed state and instance operations safely.

Generic Class Definition

class GenericStack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }
}

const numberStack = new GenericStack<number>();
numberStack.push(10);
numberStack.push(20);
console.log(numberStack.pop()); // 20 (type-safe number!)

Static Members Note

Static members of a class cannot use the class's type parameters because static properties are shared across all instances regardless of T.

class Container<T> {
  // static defaultItem: T; // Compile error!
}

TL;DR

  • Generic classes allow state storage and member methods to adapt to defined types.
  • Static class members cannot reference the instance type parameter <T>.