Destructured discriminants
Concept and syntax
When a discriminated union is destructured into const bindings, TypeScript can preserve the connection between the tag and payload. Checking the tag then narrows the payload. Separately reassignable bindings may lose that correlation; prefer keeping the object intact if values must change independently.
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 Msg={kind:"text"; payload:string}|{kind:"count"; payload:number};function show(m:Msg){ const {kind,payload}=m; return kind==="text" ? payload.toUpperCase() : payload.toFixed(1); }console.log(show({kind:"text",payload:"hi"}),show({kind:"count",payload:3}));Expected output:
HI 3.0Common mistake
Intentionally invalid; compile separately and do not execute.
type Msg={kind:"text"; payload:string}|{kind:"count"; payload:number};function show(m:Msg){ let {kind,payload}=m; if(kind==="text") return payload.toUpperCase(); }Expected diagnostic: TS2339. Mutable destructured bindings do not retain this correlation. Use const or check the original object.
Practice and recap
Add a boolean payload variant and narrow its destructured payload.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Destructured discriminants — 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 Msg={kind:"text"; payload:string}|{kind:"count"; payload:number};function show(m:Msg){ const {kind,payload}=m; return kind==="text" ? payload.toUpperCase() : payload.toFixed(1); }console.log(show({kind:"text",payload:"hi"}),show({kind:"count",payload:3}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Msg={kind:"text"; payload:string}|{kind:"count"; payload:number};function show(m:Msg){ let {kind,payload}=m; if(kind==="text") return payload.toUpperCase(); }