Exhaustiveness with never
Concept and syntax
After all variants have been handled, a discriminated union narrows to never in the remaining branch. Assigning the remainder to never is a compile-time exhaustiveness check. If a variant is added but not handled, the assignment fails. Throw in the unreachable branch as a runtime safeguard.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Job = {kind:"done"} | {kind:"waiting"};function show(j:Job):string { switch(j.kind){case "done":return "ok";case "waiting":return "wait";} const unreachable:never=j; throw new Error(String(unreachable));}console.log(show({kind:"done"}),show({kind:"waiting"}));Expected output:
ok waitCommon mistake
Intentionally invalid; compile separately and do not execute.
type Job = {kind:"done"} | {kind:"waiting"};function show(j:Job){ if(j.kind === "done") return; const rest:never=j; }Expected diagnostic: TS2322. The waiting variant remains. Handle it before the never assignment.
Practice and recap
Add a cancelled variant and observe the exhaustiveness error before fixing it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exhaustiveness with never — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Job = {kind:"done"} | {kind:"waiting"};function show(j:Job):string { switch(j.kind){case "done":return "ok";case "waiting":return "wait";} const unreachable:never=j; throw new Error(String(unreachable));}console.log(show({kind:"done"}),show({kind:"waiting"}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Job = {kind:"done"} | {kind:"waiting"};function show(j:Job){ if(j.kind === "done") return; const rest:never=j; }