Discriminated unions
Relay receives four webhook events for every job: queued, started, failed, succeeded. A handler
that forgets one doesn’t crash. It silently drops the event, the job never leaves running, and
you find out from a customer. The fix is to make forgetting a type error.
The last lesson used status to tell job states apart. Events work the same way. A
discriminated union is a union of object types that share one literal field, the
discriminant. Checking that field narrows the whole object.
The discriminant
Section titled “The discriminant”type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number } | { readonly _tag: "JobStarted"; readonly jobId: string; readonly worker: string; readonly at: number } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string; readonly at: number } | { readonly _tag: "JobSucceeded"; readonly jobId: string; readonly at: number }_tag is a common name for the discriminant, and Relay uses it for every tagged type. Any field
with a literal type works, though: status was the discriminant in lesson 1. What matters is
that each member has a different literal in that field.
Switch on the tag
Section titled “Switch on the tag”type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number } | { readonly _tag: "JobStarted"; readonly jobId: string; readonly worker: string; readonly at: number } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string; readonly at: number } | { readonly _tag: "JobSucceeded"; readonly jobId: string; readonly at: number }
function describe(event: JobEvent): string { switch (event._tag) { case "JobQueued": return `${event.jobId} queued` // event is the JobQueued member case "JobStarted": return `${event.jobId} on ${event.worker}` // worker exists here case "JobFailed": return `${event.jobId} failed: ${event.reason}` // reason exists here case "JobSucceeded": return `${event.jobId} succeeded` }}In each case, event is narrowed to the one member with that tag. worker is only readable
under "JobStarted", so you can’t print a worker for an event that has none.
Destructuring the tag
Section titled “Destructuring the tag”You can pull the tag out into a const and switch on that. TypeScript (4.4 and later) still
narrows event, because it knows _tag came from event:
type JobEvent = | { readonly _tag: "JobStarted"; readonly jobId: string; readonly worker: string } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string }
function describe(event: JobEvent): string { const { _tag } = event switch (_tag) { case "JobStarted": return event.worker // event is the JobStarted member case "JobFailed": return event.reason // event is the JobFailed member }}This only works when the tag is destructured into a const (or a parameter that’s never
reassigned). A let or a value read from somewhere else breaks the link.
Sharing a branch
Section titled “Sharing a branch”Two tags that need the same handling can share a branch. An empty case falls through to the
next one. M1’s noFallthroughCasesInSwitch allows that, because it only complains about cases
that have code:
type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string }
function isTerminal(event: JobEvent): boolean { switch (event._tag) { case "JobFailed": case "JobSucceeded": return true // event is JobFailed | JobSucceeded case "JobQueued": return false }}Inside the shared branch, event is the union of the listed members, so only fields they all
have (jobId) are readable.
Exhaustiveness
Section titled “Exhaustiveness”If a new event is added and a switch has no case for it, the function falls off the end and
returns undefined. Make that a compile error by handling default with absurd, a small helper that
only accepts never (the exhaustiveness trick from the unknown lesson):
type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string }
function absurd(x: never): never { throw new Error(`unhandled: ${JSON.stringify(x)}`)}
function label(event: JobEvent): string { switch (event._tag) { case "JobQueued": return "queued" case "JobSucceeded": return "succeeded" default: return absurd(event) // event is never here }}After every case, nothing is left for event to be, so its type is never. If one case is
missing, event is still that member in default, and passing it to absurd fails. If you
don’t want a helper, event satisfies never does the same check:
type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string }
function label(event: JobEvent): string { switch (event._tag) { case "JobQueued": return "queued" case "JobSucceeded": return "succeeded" default: event satisfies never throw new Error("unhandled event") }}The absurd version also throws at runtime if bad data gets past the types, so Relay’s own
code uses it.
A table that can’t miss a tag
Section titled “A table that can’t miss a tag”When the per-event result is just data, use a lookup table instead of a switch.
JobEvent["_tag"] is the type of the _tag field of any member: here, the union of the four
tag strings. Record<K, V> is an object with one V value for each key in K:
type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobStarted"; readonly jobId: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string }
type Tag = JobEvent["_tag"] // "JobQueued" | "JobStarted" | "JobSucceeded"
// @ts-expect-error: JobSucceeded is missingconst labels: Record<Tag, string> = { JobQueued: "Queued", JobStarted: "Started"}Add the missing key and the error goes away.
Adding a fifth event
Section titled “Adding a fifth event”Say Relay starts receiving JobCancelled. Add one member to the union:
type JobEvent = | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string } | { readonly _tag: "JobCancelled"; readonly jobId: string; readonly by: string }
function absurd(x: never): never { throw new Error(`unhandled: ${JSON.stringify(x)}`)}
function label(event: JobEvent): string { switch (event._tag) { case "JobQueued": return "queued" case "JobSucceeded": return "succeeded" default: // @ts-expect-error: event is JobCancelled here, not never return absurd(event) }}Every switch with an absurd default and every Record<Tag, ...> table now fails to compile.
The error list is your to-do list: add the JobCancelled case to each one, and the errors
disappear. Without that, you’d grep for "JobSucceeded" and hope.
Exercise
Section titled “Exercise”describe handles two of four events. Handle the other two so absurd(event) type-checks. The
tests check what each event turns into.
- A discriminated union is a union whose members share one literal field. Checking it narrows the whole object.
switch (event._tag)narrowseventin each case. Destructuring the tag into aconststill narrowsevent.- Empty
cases share a branch. Inside it,eventis the union of those members. default: return absurd(event)andevent satisfies neverturn a missing case into a compile error.Record<JobEvent["_tag"], V>is a table that must list every tag.- Adding a member to the union makes the compiler list every place to update.
Further reading
Section titled “Further reading”- TypeScript 4.4 release notes: control flow for aliased conditions and discriminants.
- Handbook: Narrowing: discriminated unions and exhaustiveness checking.