Typed Dispatch Table Handles Every Event Kind
A mapped handler object keyed by the event discriminant makes dispatch exhaustive: adding a kind without a handler breaks the object literal at compile time.
Code
type Event =
| { kind: "deploy"; env: string }
| { kind: "alert"; code: number }
| { kind: "ping" };
const handlers: { [K in Event["kind"]]: (event: Extract<Event, { kind: K }>) => string } = {
deploy: (e) => `deploying to ${e.env}`,
alert: (e) => `alert ${e.code}`,
ping: () => "pong",
};
// dispatch is exhaustive: adding a kind without a handler breaks the object literal
function dispatch(event: Event): string {
return handlers[event.kind](event);
}
const events: Event[] = [
{ kind: "deploy", env: "staging" },
{ kind: "alert", code: 503 },
{ kind: "ping" },
];
for (const event of events) {
console.log(dispatch(event));
}
// Extract pulls the single variant back out of the union for one handler
type AlertEvent = Extract<Event, { kind: "alert" }>;
const alertOnly: AlertEvent = { kind: "alert", code: 429 };
console.log(handlers.alert(alertOnly));Output
Captured from a sandboxed run of this snippet in the build pipeline.
deploying to staging
alert 503
pong
alert 429How it works
Typed Dispatch Table Handles Every Event Kind is built around the function dispatch.
The file repeats itself only inside for (const event of events).
Caveats
- Self-contained — no imports beyond what the runtime already provides.
Using it
Signature: function dispatch(event: Event)
Key statements
const handlers: { [K in Event["kind"]]: (event: Extract<Event, { kind: K }>) => string } = {
deploy: (e) => `deploying to ${e.env}`,
alert: (e) => `alert ${e.code}`,
ping: () => "pong",
};
return handlers[event.kind](event);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `dispatch` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.