Typed Event Emitter
What you'll build
An EventEmitter class that uses a mapped type to map event names to payload types. Emitting or listening to an event with the wrong payload type is a compile error.
Goals
- Use mapped types to define event maps
- Enforce type-safe event payloads
- Practice generic class design
- Build a publish-subscribe pattern with full type safety
Prerequisites
- Generics
- Mapped types
- Classes
Steps
- 1
Define the event map interface
Create an interface that maps event names to their payload types. This is the source of truth for all events.
Codeinterface Events { login: { userId: string; timestamp: number }; logout: { userId: string }; error: { code: number; message: string }; }Expected result
An event map with three events, each with a specific payload type.
- 2
Write the typed EventEmitter class
Create a generic class parameterized by the event map. The on and emit methods use keyof and indexed access types to enforce payload types.
Codeclass TypedEmitter<E extends Record<string, any>> { private handlers: { [K in keyof E]?: ((payload: E[K]) => void)[] } = {}; on<K extends keyof E>(event: K, handler: (payload: E[K]) => void) { (this.handlers[event] ||= []).push(handler); } emit<K extends keyof E>(event: K, payload: E[K]) { this.handlers[event]?.forEach(h => h(payload)); } }Expected result
A fully typed event emitter. Wrong payload types are compile errors.
- 3
Use the typed emitter
Instantiate the emitter with your Events type. TypeScript now checks every on and emit call against the event map.
Codeconst emitter = new TypedEmitter<Events>(); emitter.on("login", (p) => console.log(p.userId)); emitter.emit("login", { userId: "abc", timestamp: Date.now() }); // emitter.emit("login", { wrong: true }); // Compile error!Expected result
Event names and payloads are fully type-checked. Typos or wrong shapes are caught at compile time.
- 4
Add type guards & runtime checks
Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.
Codetype User = { id: number; name: string }; function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const obj = value as Record<string, unknown>; return typeof obj.id === "number" && typeof obj.name === "string"; } // Usage with unknown input const data: unknown = JSON.parse(rawJson); if (isUser(data)) { console.log(data.name); // TS knows data is User here } else { console.error("Invalid user data"); }Expected result
When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.
- 5
Add generic utility functions
Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.
Codefunction groupBy<T, K extends string | number>( items: T[], keyFn: (item: T) => K ): Record<K, T[]> { const result = {} as Record<K, T[]>; for (const item of items) { const key = keyFn(item); (result[key] ??= []).push(item); } return result; } // Usage const byAge = groupBy(users, u => u.age);Expected result
groupBy groups any array by key, returning a type-safe Record.
Try it yourself
What you learned
You built a type-safe event emitter where event names and payloads are verified at compile time. This pattern — using a record type as a type-level map — is widely used in real-world TypeScript libraries for APIs, stores, and event systems.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.