Destructured Discriminants Keep Union Narrowing
Destructure discriminated union fields into const bindings before branching so TypeScript still narrows payload types inside switch and if statements.
Code
type JobEvent =
| { kind: 'started'; payload: { workerId: string } }
| { kind: 'completed'; payload: { durationMs: number } }
| { kind: 'failed'; payload: { exitCode: number; reason: string } };
function formatJobEvent(event: JobEvent): string {
// TypeScript narrows `payload` alongside destructured `kind` when both are const
const { kind, payload } = event;
switch (kind) {
case 'started':
return `worker ${payload.workerId} active`;
case 'completed':
return `finished in ${payload.durationMs}ms`;
case 'failed':
return `exit ${payload.exitCode}: ${payload.reason}`;
}
}
const timeline: JobEvent[] = [
{ kind: 'started', payload: { workerId: 'w-4' } },
{ kind: 'completed', payload: { durationMs: 142 } },
{ kind: 'failed', payload: { exitCode: 2, reason: 'checksum mismatch' } },
];
for (const item of timeline) {
console.log(formatJobEvent(item));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
worker w-4 active
finished in 142ms
exit 2: checksum mismatchInside the implementation — Destructured Discriminants Keep Union Narrowing
Everything happens inside the function formatJobEvent.
A single loop drives the file — for (const item of timeline).
What to watch for
- No dependencies section needed; the standard library is the whole story.
Using it
Featured function interface shows function formatJobEvent(event: JobEvent)
Key statements
return `exit ${payload.exitCode}: ${payload.reason}`;
return `finished in ${payload.durationMs}ms`;
return `worker ${payload.workerId} active`;
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `formatJobEvent` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.