Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type

Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.

~6 min readTypeScript
#TypeScript#Type Narrowing#Pattern Matching
3D illustration of tagged union data blocks branching into exhaustive switch cases with a secure never-type barrier

A discriminated union is a union of object types that each carry a property whose type is a distinct literal, so that a comparison against that property narrows the whole union to one member. The discriminant turns an untagged union — where overlapping shapes force structural guessing — into a closed set the compiler can branch on soundly and count. The never type closes the loop: once every member has been handled, the leftover value has no type left, and assigning it to never makes a missing case a compile error instead of a runtime surprise.

Quick Summary

  • The discriminant must be a literal type: string, number, boolean, an enum member, null, or undefined. A string-typed property narrows nothing.
  • Narrowing works through switch, ===/!==, in, instanceof, and user-defined type guards; each narrows one member at a time.
  • never is the bottom type: never is assignable to every type, and nothing except never is assignable to never. That asymmetry is what an exhaustiveness check tests.
  • The canonical check is default: { const _: never = value; } or a helper function assertNever(v: never): never { throw ... }.
  • A Record<Kind, Handler> map moves the exhaustiveness error to the definition of the map, so adding a member fails once instead of at every switch.
  • Duplicate discriminant values across members silently disable narrowing and let the never check pass while a case is still missing.
  • Adding a member is supposed to break switches: every build error is a place that needs a decision, and default: return fallback throws that signal away.
  • None of this exists at runtime. JSON arrives with any string, so the union must be parsed at the boundary before it is trusted.

Basic syntax and type signatures

typescript
type Shape = | { kind: "circle"; radius: number } | { kind: "square"; side: number } | { kind: "rect"; width: number; height: number }; function area(s: Shape): number { switch (s.kind) { case "circle": return Math.PI * s.radius ** 2; // s: { kind: "circle"; radius: number } case "square": return s.side ** 2; case "rect": return s.width * s.height; } }

Adding one case to area is a behavior change; adding one member to Shape is a compile error at that function, because the compiler now sees a fall-through path where the return type is number and the function may end without returning:

typescript
// after adding { kind: "triangle"; base: number; height: number } to Shape // TS2366: Function lacks ending return statement and return type does not include 'undefined'.

The explicit version of the same check, which does not depend on noImplicitReturns:

typescript
function assertNever(value: never, context = "value"): never { throw new Error(`Unhandled ${context}: ${JSON.stringify(value)}`); } function areaChecked(s: Shape): number { switch (s.kind) { case "circle": return Math.PI * s.radius ** 2; case "square": return s.side ** 2; case "rect": return s.width * s.height; default: return assertNever(s); // s must be never here } }

assertNever has a parameter of type never. If one member is still unhandled, s in the default branch is that member, not never, and the call itself fails with TS2345: Argument of type 'Triangle' is not assignable to parameter of type 'never'. The error lands on the call, pointing at the missing case.

Comparison of exhaustiveness techniques

TechniqueWhere the error appearsDepends onRuntime safetyBest for
const _: never = value in defaultthe assignmentstrictNullChecks, a default branchnonelocal switches, quick checks
assertNever(value) helperthe call argumenta default branchthrowsshared code, better messages
noImplicitReturns + full switchthe function signaturecompiler optionnonereturning functions with no default
Record<Kind, Handler> mapthe object literalthe key unionnonedispatch tables, plugin registries
satisfies never on a residualthe satisfies callTypeScript 4.9+noneone-liner checks in tests
runtime parse (zod, hand-written)the parse calla schemayesdata from JSON, headers, forms

The first four are compile-time only. They prove that the code handles every member the type declares, not that the value at hand is one of them, which is why anything crossing a process boundary needs the last row as well.

Practical edge cases and deep dives

1. A non-literal discriminant narrows nothing

typescript
interface BadEvent { type: string; payload: unknown } // no literal interface GoodEvent { type: "click" | "submit"; payload: unknown } function bad(e: BadEvent) { switch (e.type) { case "click": break; case "submit": break; default: { const _: never = e; // TS2322: BadEvent is not assignable to never } } }

BadEvent is a single type, not a union, so there is nothing to narrow and the never assignment fails immediately — a useful first error, but the usual outcome is worse: the property is declared string, the object type is written once, and the code compares against string literals that the compiler treats as unreachable, producing TS2367: This comparison appears to be unintentional because the types 'string' and '"click"' have no overlap only when the comparison is provably disjoint. Literal types can be recovered without rewriting the type:

typescript
const EVENTS = { click: "click", submit: "submit" } as const; type EventName = (typeof EVENTS)[keyof typeof EVENTS]; interface Event { type: EventName }

The failure mode to watch for in code review is a widening literal: { type: "click" } stored in an object whose field is annotated string widens at the annotation, so the union dissolves before it ever reaches the switch. as const on the object literal or satisfies Shape on it preserves the member type.

2. Duplicate discriminants that pass the check

typescript
type Job = | { status: "pending"; queuedAt: Date } | { status: "pending"; retryAt: Date } // same discriminant | { status: "done"; finishedAt: Date }; function handle(j: Job) { switch (j.status) { case "pending": /* j is the union of both pending members */ break; case "done": break; default: { const _: never = j; // no error: "pending" is fully covered } } }

Both pending members collapse into one case, and inside it the compiler only lets you touch properties present on both — j.queuedAt is an error because the second member lacks it. The never check passes because the coverage is complete at the level of discriminant values; the two members were simply never distinguishable. The fix is either a distinct value ("queued" and "retrying") or a nested discriminant. The same collapse happens when a member's discriminant is string or a wide enum rather than one literal, and it is easy to miss because nothing errors.

3. in narrowing, optional discriminants, and partially tagged unions

typescript
type Result<T> = | { ok: true; value: T } | { ok: false; error: Error } | { ok?: undefined; pending: true }; // optional discriminant function unwrap<T>(r: Result<T>): T { if (r.ok === true) return r.value; if (r.ok === false) throw r.error; // here r is { ok?: undefined; pending: true } throw new Error("pending"); }

r.ok === true narrows by the literal true; r.ok === false by false; a truthiness check (if (r.ok)) narrows both branches as well, but it also accepts any truthy value if the union later gains one. Optional discriminants work because undefined is a literal type — but note that a member with ok?: undefined is also matched by r.ok === undefined, which is exactly what makes the third branch reachable. For unions discriminated by presence rather than value, in is the tool:

typescript
type Node2 = { value: number; left: Node2 } | { value: number; leaf: true }; function sum(n: Node2): number { if ("leaf" in n) return n.value; // narrowed to the leaf member return n.value + sum(n.left); }

in narrows only when the property is unique to some members. If both members declare left (one as undefined), the check narrows nothing.

4. Distributive helpers: Extract, Exclude, and the Omit trap

typescript
type Shape2 = | { kind: "circle"; radius: number; label: string } | { kind: "square"; side: number; label: string }; type Circle = Extract<Shape2, { kind: "circle" }>; // one member type WithoutCircle = Exclude<Shape2, { kind: "circle" }>; // Omit is not distributive: it collapses the union into one object type. type Broken = Omit<Shape2, "kind">; // { radius?: ...; side?: ...; label: string } type Fixed = Shape2 extends infer S ? S extends { kind: string } ? Omit<S, "kind"> : never : never;

Omit<T, K> is defined as Pick<T, Exclude<keyof T, K>>, and keyof of a union is the intersection of its keys, so the result is one object type with the optional members of every branch. Any mapped utility applied to a union needs a distributive wrapper, written either as a conditional type over a naked type parameter (T extends unknown ? ... : never) or with DistributiveOmit<T, K> = T extends any ? Omit<T, K> : never. Reducers are where this bites: Omit<Action, "type"> in a reducer's payload type loses the discriminant and every case sees the union again.

5. Exhaustiveness against real data

typescript
type Payload = { kind: "text"; body: string } | { kind: "image"; url: string }; const KINDS = ["text", "image"] as const; function parsePayload(input: unknown): Payload { if (typeof input !== "object" || input === null) throw new Error("not an object"); const kind = (input as { kind?: unknown }).kind; if (!KINDS.includes(kind as (typeof KINDS)[number])) { throw new Error(`unknown kind: ${String(kind)}`); } if (kind === "text") { const body = (input as { body?: unknown }).body; if (typeof body !== "string") throw new Error("body must be a string"); return { kind, body }; } const url = (input as { url?: unknown }).url; if (typeof url !== "string") throw new Error("url must be a string"); return { kind: "image", url }; }

The KINDS array is the runtime mirror of the union, and keeping it next to the type is the cheapest way to notice drift: a satisfies check (const KINDS = [...] as const satisfies readonly Payload["kind"][]) catches a member removed from the array but not one added to the union, so the array is usually derived from a hand-written schema instead. Whatever mechanism is chosen, the invariant matters: after parsePayload, the value is a Payload the compiler can switch over exhaustively, and before it, it is unknown. A cast (input as Payload) skips the parse and produces a value that passes every compile-time check while its kind is "imag".

Common mistakes and compiler errors

Error or symptomCauseFix
TS2322: Type 'Triangle' is not assignable to type 'never'a new member has no caseadd the case; the error names the missing member
TS2345: Argument of type 'Shape' is not assignable to parameter of type 'never'assertNever called with an unhandled membersame: handle the member
TS2367: This comparison appears to be unintentionala case is duplicated, or the value was already narrowed to another memberremove the redundant case
No error, but a case is silently skippedduplicate discriminants, or a string-typed discriminantuse unique literal values
TS2366: Function lacks ending return statementa switch with no default and a declared return typeintended when every member is covered — otherwise add the missing case
A new member compiles everywherea default: branch returns a fallbackreplace the fallback with assertNever
Narrowing vanishes after a helper callthe helper takes the union and returns boolean instead of a type predicatereturn value is Member
Omit on a union loses the discriminantOmit is not distributivewrap it in a conditional type
TS2339 when reading the discriminantone member of the union lacks the propertydeclare the discriminant on every member, optional if needed
Runtime crash on default that "cannot happen"the value came from JSON and was cast, not parsedparse at the boundary

The design rule that makes the pattern worth the boilerplate: never write a default branch that produces a domain value. A default that throws through assertNever is a compile-time assertion plus a runtime guard; a default that returns 0, null, or a fallback string converts a build failure into silent data loss the day a member is added. When a fallback genuinely is correct — a UI that ignores unknown event kinds from a forward-compatible server — that decision belongs in an explicit parser that maps unknown input to a known member, not in the switch that was supposed to be exhaustive.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.