TypeScriptTypeScript18 min read

Generic Classes

Build reusable data structures and services using generic classes.

David Miller
January 7, 2026
0.6k17

Generics also work with classes.

    ## Example: Box
    
    ```ts
    class Box<T> {
      value: T;
    
      constructor(val: T) {
        this.value = val;
      }
    
      get(): T {
        return this.value;
      }
    }
    
    const numBox = new Box<number>(10);
    const strBox = new Box("hello");
    ```
    
    ## Example: Generic stack
    
    ```ts
    class Stack<T> {
      private items: T[] = [];
    
      push(item: T) {
        this.items.push(item);
      }
    
      pop(): T | undefined {
        return this.items.pop();
      }
    }
    ```
    
    ## Graph
    ```mermaid
    flowchart TD
      A[Stack<T>] --> B[T = number]
      A --> C[T = string]
    ```
    
    ## Remember
    - Generic classes adapt to types
    - Great for reusable utilities
    
#TypeScript#Intermediate#Generics