Discriminated unions
Concept and syntax
A discriminated union gives each variant a shared literal tag, such as kind. Checking the tag narrows the whole object, preserving the relationship between status and data. Prefer separate variant contracts over unrelated optional fields when data depends on state.
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 Result = {kind:"ok"; value:number} | {kind:"error"; message:string};function show(r:Result){ return r.kind === "ok" ? String(r.value) : r.message; }console.log(show({kind:"ok",value:7}),show({kind:"error",message:"retry"}));Expected output:
7 retryCommon mistake
Intentionally invalid; compile separately and do not execute.
type Result = {kind:"ok"; value:number} | {kind:"error"; message:string};function show(r:Result){ return r.value; }Expected diagnostic: TS2339. Check kind before accessing value. The error variant has no value.
Practice and recap
Add a third tagged variant and update show.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Discriminated unions — 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 Result = {kind:"ok"; value:number} | {kind:"error"; message:string};function show(r:Result){ return r.kind === "ok" ? String(r.value) : r.message; }console.log(show({kind:"ok",value:7}),show({kind:"error",message:"retry"}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Result = {kind:"ok"; value:number} | {kind:"error"; message:string};function show(r:Result){ return r.value; }