Lesson 8 of 8
Practice & Quiz - OOP in TypeScript
Consolidate your understanding of TypeScript OOP - classes, access modifiers, interfaces, abstract classes, generics, and Dependency Injection - with a practical exercise and 5 quiz questions.
Practical: Generic Typed Event Emitter
Practical: Generic Typed Event Emitter
// Build a fully typed, generic event emitter from scratch
type Listener<T> = (payload: T) => void;
class EventEmitter<Events extends Record<string, unknown>> {
private listeners = {} as { [K in keyof Events]?: Listener<Events[K]>[] };
on<K extends keyof Events>(event: K, cb: Listener<Events[K]>): this {
(this.listeners[event] ??= []).push(cb);
return this; // enables method chaining
}
off<K extends keyof Events>(event: K, cb: Listener<Events[K]>): void {
this.listeners[event] = this.listeners[event]?.filter(l => l !== cb);
}
emit<K extends keyof Events>(event: K, payload: Events[K]): void {
this.listeners[event]?.forEach(l => l(payload));
}
}
// Strongly-typed event map - every event name + payload shape defined once:
type AppEvents = {
"task:created": { id: number; title: string };
"task:deleted": { id: number };
"user:logged-in": { userId: number };
};
const emitter = new EventEmitter<AppEvents>();
emitter
.on("task:created", ({ id, title }) => console.log(`Task ${id}: ${title}`))
.on("user:logged-in", ({ userId }) => console.log(`User ${userId} signed in`));
emitter.emit("task:created", { id: 1, title: "Launch" }); // ✅ typed
// emitter.emit("task:created", { id: "x" }); // ❌ id must be numberDiagram
Loading diagram…
TypeScript = JavaScript + static types → fewer bugs, better tooling
Module Quiz
Module Quiz
Question 1 of 5Which access modifier allows a member to be accessed inside the declaring class AND its subclasses, but NOT from outside?
Finished this lesson?
0 of 8 in Module 4