Lesson 5 of 8
Generics in Classes & Inheritance
Generic classes accept type parameters that flow through all their methods and properties. Combined with inheritance and constraints, they enable flexible base classes like repositories, caches, and event emitters that work for any entity type while remaining fully type-safe.
Generic Classes - Base Repositories & Typed Containers
// ── Generic class ────────────────────────────────────────────
class Stack<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.at(-1); }
get size(): number { return this.items.length; }
isEmpty(): boolean { return this.items.length === 0; }
toArray(): readonly T[] { return [...this.items]; }
}
const taskStack = new Stack<Task>();
taskStack.push(task1);
const top = taskStack.peek(); // Type: Task | undefined
// ── Generic base repository ────────────────────────────────────
interface Entity { readonly id: number; }
abstract class BaseRepository<T extends Entity> {
protected entities = new Map<number, T>();
findById(id: number): T | undefined {
return this.entities.get(id);
}
findAll(): T[] {
return [...this.entities.values()];
}
save(entity: T): T {
this.entities.set(entity.id, entity);
return entity;
}
delete(id: number): boolean {
return this.entities.delete(id);
}
count(): number {
return this.entities.size;
}
}
// Concrete repository extends generic base - FREE CRUD methods:
class TaskRepositoryImpl extends BaseRepository<Task> {
findByStatus(status: TaskStatus): Task[] {
return this.findAll().filter((t) => t.status === status);
}
findOverdue(): Task[] {
const now = new Date();
return this.findAll().filter(
(t) => t.dueDate !== null && t.dueDate < now && t.status !== "done"
);
}
}
class UserRepositoryImpl extends BaseRepository<User> {
findByEmail(email: string): User | undefined {
return this.findAll().find((u) => u.email === email);
}
}
// Both get findById, findAll, save, delete, count - typed correctly:
const taskRepo = new TaskRepositoryImpl();
const userRepo = new UserRepositoryImpl();
taskRepo.findByStatus("todo"); // Task[]
userRepo.findByEmail("alice@co.com"); // User | undefined
// ── Generic event emitter ─────────────────────────────────────
type EventMap = Record<string, unknown>;
class TypedEventEmitter<Events extends EventMap> {
private listeners = {} as { [K in keyof Events]?: Array<(payload: Events[K]) => void> };
on<K extends keyof Events>(event: K, listener: (payload: Events[K]) => void): this {
(this.listeners[event] ??= []).push(listener);
return this;
}
emit<K extends keyof Events>(event: K, payload: Events[K]): void {
this.listeners[event]?.forEach((l) => l(payload));
}
}
// Usage with Task Manager events:
type TaskEvents = {
"task:created": { task: Task };
"task:completed": { taskId: number; completedAt: Date };
"task:deleted": { taskId: number };
};
const emitter = new TypedEventEmitter<TaskEvents>();
emitter.on("task:created", ({ task }) => console.log("Created:", task.title));
emitter.on("task:completed", ({ taskId }) => console.log("Done:", taskId));
// emitter.emit("task:unknown", {}); // ❌ Error - unknown eventCommon Mistakes
- Forgetting the `T extends Entity` constraint on repositories - without the constraint, TypeScript cannot access `entity.id` inside the class.
- Creating separate repositories from scratch instead of extending a generic base - copy-paste of CRUD logic across repositories is a maintenance nightmare. A generic base eliminates it.
- Using `any` instead of the generic type parameter inside the class - inside a generic class, use `T` consistently. Using `any` anywhere in the class breaks the type flow.
Tip
Tip
Practice Generics in Classes Inheritance in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Generics in Classes & Inheritance
Practice Task
Note
Practice Task - (1) Write a working example of Generics in Classes Inheritance from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Generics in Classes Inheritance is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Generic classes accept type parameters that flow through all their methods and properties.
- Forgetting the `T extends Entity` constraint on repositories - without the constraint, TypeScript cannot access `entity.id` inside the class.
- Creating separate repositories from scratch instead of extending a generic base - copy-paste of CRUD logic across repositories is a maintenance nightmare. A generic base eliminates it.
- Using `any` instead of the generic type parameter inside the class - inside a generic class, use `T` consistently. Using `any` anywhere in the class breaks the type flow.
Finished this lesson?