Typescript Foundations / Generics

Generic Classes

A Generic Class allows you to create a class that works with any type(s), determined when you create an instance of the class.


✅ Basic Syntax

class Box<T> {
  content: T;

  constructor(value: T) {
    this.content = value;
  }

  getContent(): T {
    return this.content;
  }
}

const numberBox = new Box<number>(123);
const stringBox = new Box<string>("TypeScript");

Here:

  • T is a type placeholder.

  • When creating new Box<number>(), T becomes number.


🧮 Multiple Type Parameters

class Pair<K, V> {
  key: K;
  value: V;

  constructor(key: K, value: V) {
    this.key = key;
    this.value = value;
  }
}

const pair = new Pair<string, number>("age", 25);

🛠️ Class with Methods Using Generics

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

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

  getAll(): T[] {
    return this.items;
  }
}

const stringCollection = new Collection<string>();
stringCollection.add("apple");
stringCollection.add("banana");

const allStrings = stringCollection.getAll(); // string[]

⛓️ Constraining Generic Types

Use extends to restrict the kinds of types allowed for T.

interface HasId {
  id: number;
}

class EntityManager<T extends HasId> {
  private entities: T[] = [];

  add(entity: T) {
    this.entities.push(entity);
  }

  getById(id: number): T | undefined {
    return this.entities.find(e => e.id === id);
  }
}

const manager = new EntityManager<{ id: number; name: string }>();
manager.add({ id: 1, name: "Tisha" });

📦 Default Generic Type

class ApiResponse<T = any> {
  constructor(public data: T, public success: boolean) {}
}

const response = new ApiResponse("All good!", true); // T = string
const defaultResponse = new ApiResponse(123, true);   // T = number


📌 Summary

Feature

Example

Single Generic

class Box<T> { ... }

Multiple Generics

class Pair<K, V> { ... }

Generic Methods

add(item: T): void

Constraints

T extends HasId

Default Type

class MyClass<T = string>


💡 Use Cases

  • Data managers (e.g., EntityManager<T>)

  • Form handlers

  • Caching layers

  • API response models

  • Stacks, queues, collections