Type-safe event emitters
An event map ties each event name to its payload, as in mitt and typed Node emitters. A free TypeScript lesson with examples.
More on Patterns from open source
Keep learning
Overview
chapters · patterns from open source Type-safe event emitters An event map ties each event name to its payload, so typos and wrong payloads fail at compile time.
1. The problem: strings in, any out
An event emitter (also called a bus) lets one part of the app shout an event by name. Other parts listen for that name. A classic emitter takes any string as the name. It hands listeners a value of type any (the "anything goes" type: TypeScript stops checking it). So both the sender and the listener can be wrong without a single error.
checkout.ts: untyped bus
payload: any Why no compile error? Line 2: payload is any, so TypeScript allows any field name, even one that does not exist. Line 6: the name is just a string, and "order:payed" is a valid string. The mistakes only show up when the app runs.
2. The fix: an event map plus a key generic
Describe every event once, in one type called an event map: event name → payload shape. Then make on and emit generic over the key K. keyof E: the union (one-of list) of E's key names. Here "order:paid" | "chat:typing". K extends keyof E: "K must be one of those names". E[K]: look up the type stored under key K, like reading a property, but for types.
emitter.ts: a 12-line typed emitter
what TypeScript checks K is inferred from the string you pass, then E[K] picks the payload. bus.on("order:payed", …) Argument of type '"order:payed"' is not assignable to parameter of type 'keyof Events'. The typo is not one of the map's keys, so it does not fit K. The payload for "order:paid" must have both fields. Type 'number' is not assignable to type 'string'. A typing event carries only userId. Read the first argument. K must be a key of Events. Look up the payload type for that key. Compare the object you passed with it. cents is required but missing, so the call fails. error: Property 'cents' is missing
3. Three map shapes you will meet
Libraries store the payload in different shapes. Two new pieces of syntax appear below: Tuple: a fixed-length array with a type per slot, e.g. [orderId: string, cents: number]. The names are labels only. Conditional type: a type-level if/else, written A extends B ? X : Y. Map style one payload (mitt) One object per event. Easy to extend later without breaking listeners. argument tuple (Node) Expected 3 arguments, but got 2. no payload Expected 2 arguments, but got 1.
4. The hole: a union key
A union type A | B means "either A or B". When K is a union of two event names, E[K] becomes "either payload". TypeScript then cannot tell which payload goes with which name, so a wrong pair slips through. Does this compile? Yes, no error Error: wrong payload Error: name is not a key literal "chat:typing" variable of union type pairing lost
5. How the libraries do it
Some terms first. A type argument is the type you put in angle brackets, as in mitt<Events>(). @types/node is a package that holds type descriptions for Node.js. lib.dom.d.ts is a built-in TypeScript file that describes browser APIs (types only, no code). You pass an event map as a type argument. on/emit are generic over the key. A "*" listener gets (type, payload) for every event. Node EventEmitter Recent @types/node lets EventEmitter take a map from event name to argument tuple. Without it, listeners get any[]. DOM addEventListener The same pattern built in: an event map like WindowEventMap turns "keydown" into KeyboardEvent. Socket.IO / Vue emits two maps Client-to-server and server-to-client events each get their own map. Vue’s defineEmits types emit(name, ...args) the same way. listener typed by hand Property 'key' does not exist on type 'Event'. Event is the general type shared by all events. It has no key field. Only KeyboardEvent has key, and your hand-written ": Event" threw that detail away. e: KeyboardEvent No annotation: TypeScript looks up "keydown" in WindowEventMap and finds KeyboardEvent. lib.dom.d.ts uses the exact pattern: K extends keyof WindowEventMap, listener gets WindowEventMap[K]. Event map + key generic One map, many events. Typos and payload drift become compile errors. Overloads per event
Remember
Write one map: event name → payload (or argument tuple). Make on/emit generic: K extends keyof Events, payload Events[K]. Event-name typos and wrong payloads become compile errors. Tuples give Node-style emit(name, ...args). ! Cheat code Event map type. Generic K extends keyof Map. Payload is Map[K]. That is mitt, Node and addEventListener. → Go deeper: typeof and keyof, indexed access types, how generic inference works, template literal types.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.