State models
Concept and syntax
Model each valid state as a tagged object rather than independent booleans and nullable data. Loading has no result, success carries data, and failure carries a message. This rules out contradictory shapes in typed code while leaving runtime validation at external boundaries.
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 Load = {state:"loading"} | {state:"success"; data:string[]} | {state:"failure"; error:string};function view(s:Load){ if(s.state==="loading") return "wait"; if(s.state==="success") return String(s.data.length); return s.error; }console.log(view({state:"loading"}),view({state:"success",data:["a","b"]}),view({state:"failure",error:"retry"}));Expected output:
wait 2 retryCommon mistake
Intentionally invalid; compile separately and do not execute.
type Load = {state:"loading"} | {state:"success"; data:string[]};const state:Load={state:"success"};Expected diagnostic: TS2322. Success must include its data. Build the correct variant atomically.
Practice and recap
Model a new empty state and render it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
State models — 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 Load = {state:"loading"} | {state:"success"; data:string[]} | {state:"failure"; error:string};function view(s:Load){ if(s.state==="loading") return "wait"; if(s.state==="success") return String(s.data.length); return s.error; }console.log(view({state:"loading"}),view({state:"success",data:["a","b"]}),view({state:"failure",error:"retry"}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Load = {state:"loading"} | {state:"success"; data:string[]};const state:Load={state:"success"};