Welcome back! I am Mihir, and in this lesson we will learn generic classes in TypeScript.
A generic class can store or work with different types while keeping type safety.
Basic Generic Class
class Box<T> {
constructor(public value: T) {}
getValue(): T {
return this.value;
}
}
const stringBox = new Box("Mihir");
const numberBox = new Box(100);TypeScript infers the type from the constructor value.
Explicit Generic Type
const box = new Box<string>("Hello");Here, T is explicitly set to string.
Usually inference is enough.
Generic Collection Class
class Store<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getAll(): T[] {
return this.items;
}
}Usage:
const numberStore = new Store<number>();
numberStore.add(10);
numberStore.add(20);
const userStore = new Store<{ id: number; name: string }>();
userStore.add({ id: 1, name: "Mihir" });Generic Class Methods
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
}The class keeps the same item type across all methods.
Implementing a Generic Interface
interface Repository<T> {
save(item: T): void;
findAll(): T[];
}
class MemoryRepository<T> implements Repository<T> {
private items: T[] = [];
save(item: T): void {
this.items.push(item);
}
findAll(): T[] {
return this.items;
}
}Generic classes work well with generic interfaces.
Common Use Cases
Generic classes are useful for:
- repositories
- queues
- caches
- data stores
- form models
- reusable service classes
Quick Recap
- Generic classes use type parameters like
class Box<T>. - The type parameter can be used in properties, methods, and constructors.
- TypeScript often infers the type from constructor arguments.
- Generic classes are useful for reusable containers and services.
- They help avoid
anywhile keeping flexibility.
Next up, we will learn Generic Constraints →.