Assignment and reachability
Concept and syntax
The declared type sets allowed assignments, but the observed type changes with control flow. Assigning a number to a string | number variable narrows it at the next use. An early return removes that branch from later reachable code. A later assignment can change a previously narrowed type.
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.
function size(x:string|number){ if(typeof x==="number") return x; return x.length; }let item:string|number="abc"; console.log(item.length); item=7; console.log(item.toFixed(1),size("tea"));Expected output:
37.0 3Common mistake
Intentionally invalid; compile separately and do not execute.
let item:string|number="abc";item=7;console.log(item.length);Expected diagnostic: TS2339. The current value is narrowed to number after assignment. Use a numeric operation.
Practice and recap
Insert an early return in a nullable input function and trace its remaining type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Assignment and reachability — 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)?
function size(x:string|number){ if(typeof x==="number") return x; return x.length; }let item:string|number="abc"; console.log(item.length); item=7; console.log(item.toFixed(1),size("tea"));Which diagnostic and explanation match the rejected example under the lesson settings?
let item:string|number="abc";item=7;console.log(item.length);