79. Typed application state
Module 16 · approximately 20 minutes
Open Interactive LessonDiscover and predict
What does typed application state let the compiler check, and what still needs a runtime test?
Understand
State should represent valid combinations and be updated through clear operations. A discriminated union can distinguish idle, ready and error states, while a reducer can make transitions explicit. The type system checks the model but does not prevent stale asynchronous responses or persist state automatically. Derive the UI from actual state rather than mutating unrelated labels independently.
Important source operations
- Line 1:
type State={count:number};type Action={type:"increment"}|{type:"reset"}; - This declaration describes a static contract and does not construct or validate runtime data. Actual checker declaration information: State: { count: number; }; Action: { type: "increment"; } | { type: "reset"; }.
- Line 2:
function reduce(state:State,action:Action):State{return {count:action.type === "increment"?state.count+1:0};} - The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests. Actual checker declaration information: reduce: (state: State, action: Action) => State; state: { count: number; }; action: { type: "increment"; } | { type: "reset"; }.
- Line 3:
console.log(reduce({count:2},{type:"increment"}).count); - Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.
Working concept in practice
State should represent valid combinations and be updated through clear operations. A discriminated union can distinguish idle, ready and error states, while a reducer can make transitions explicit. The type system checks the model but does not prevent stale asynchronous responses or persist state automatically. Derive the UI from actual state rather than mutating unrelated labels independently.
main.ts
type State={count:number};type Action={type:"increment"}|{type:"reset"};
function reduce(state:State,action:Action):State{return {count:action.type === "increment"?state.count+1:0};}
console.log(reduce({count:2},{type:"increment"}).count);Exact authored reference result
{
"diagnostics": [],
"logs": [
"3"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Investigate the compiler or runtime fault
Predict the result of the supplied wrong operation. Read actual compiler feedback; if it compiles, investigate the real runtime mismatch instead. Fault: {type:"unknown"}
main.ts
type State={count:number};type Action={type:"unknown"}|{type:"reset"};
function reduce(state:State,action:Action):State{return {count:action.type === "increment"?state.count+1:0};}
console.log(reduce({count:2},{type:"increment"}).count);Exact authored reference result
{
"diagnostics": [
{
"code": 2367,
"category": "Error",
"message": "This comparison appears to be unintentional because the types '\"unknown\" | \"reset\"' and '\"increment\"' have no overlap.",
"file": "main.ts",
"line": 2,
"column": 64,
"start": 134,
"length": 27
},
{
"code": 2322,
"category": "Error",
"message": "Type '\"increment\"' is not assignable to type '\"unknown\" | \"reset\"'.",
"file": "main.ts",
"line": 3,
"column": 31,
"start": 211,
"length": 4
}
],
"logs": [],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
A compiler-clean behavioral counterexample
A valid operator implements a different business rule; static types cannot prove the intended arithmetic or predicate. This intentionally incorrect program demonstrates why runtime tests remain necessary.
main.ts
type State={count:number};type Action={type:"increment"}|{type:"reset"};
function reduce(state:State,action:Action):State{return {count:action.type !== "increment"?state.count+1:0};}
console.log(reduce({count:2},{type:"increment"}).count);Exact authored reference result
{
"diagnostics": [],
"logs": [
"0"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
An executable behavior contract
Capture the actual observable result and assert the independently authored expected output. This optional professional test pattern introduces helper/rest/async syntax; focus on the primary example first if those concepts are new.
main.ts
const __observed:string[]=[];
function __capture(...values:unknown[]):void{__observed.push(values.map(value=>typeof value==="string"?value:typeof value==="undefined"?"undefined":typeof value==="number"&&!Number.isFinite(value)?String(value):JSON.stringify(value)??String(value)).join(" "));}
type State={count:number};type Action={type:"increment"}|{type:"reset"};
function reduce(state:State,action:Action):State{return {count:action.type === "increment"?state.count+1:0};}
__capture(reduce({count:2},{type:"increment"}).count);
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["3"];if(JSON.stringify(__observed)!==JSON.stringify(expected))throw new Error("Behavior contract failed");console.log("Contract verified");}
verifyContract().catch(error=>console.log(error instanceof Error?error.message:String(error)));Exact authored reference result
{
"diagnostics": [],
"logs": [
"Contract verified"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Transfer to another useful feature
Apply the topic in a different small task. Predict the output and identify the type/runtime boundary before editing.
main.ts
type FilterState={query:string;onlyOpen:boolean};
const state:FilterState={query:"layout",onlyOpen:true};
console.log(state.query);Exact authored reference result
{
"diagnostics": [],
"logs": [
"layout"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Build and test
Repair the supplied source so it compiles under the lesson settings and produces 3. Equivalent implementations may pass the observable contract.
Hint 1
Read the first meaningful diagnostic and its source location, or compare the first runtime mismatch when the program compiles.
Hint 2
The exercise changes {type:"increment"} to {type:"unknown"}. Determine whether the contract, caller or business operation is wrong.
Hint 3
Restore {type:"increment"} or implement an equivalent correct contract. Do not hide the issue with any or an unjustified assertion; run the stated behavior check.
Explain, reflect and extend
Explain which evidence came from the compiler and which came from execution. Give a second input and a predicted result. What assumption could still fail outside this example?
Extend the useful feature with a boundary case and one invalid external input. Write the expected behavior first, then verify it using actual diagnostics and tests.
Troubleshooting
Verify the active filename, first diagnostic, actual inferred/flow type and emitted output. A type error blocks emission in this lab; an empty runtime pane is not a fabricated success. Browser examples require the DOM preview, while worker execution has no document. Project imports must refer to supplied relative files. Check runtime validation and logical operators when clean compilation still produces the wrong result.