Mutation and closure caveats
Concept and syntax
A narrowed property may be changed by another alias or a callback. The checker cannot track every mutation, and it can reject narrowing inside a closure that may run later. Capture a stable primitive value before constructing the callback instead of assuming a mutable property remains unchanged.
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 later(box:{text?:string}){ const text=box.text; if(text===undefined) return ()=>0; return ()=>text.length; }const box={text:"tea"}; const fn=later(box); box.text="x"; console.log(fn());Expected output:
3Common mistake
Intentionally invalid; compile separately and do not execute.
function later(box:{text?:string}){ if(box.text===undefined) return ()=>0; return ()=>box.text.length; }Expected diagnostic: TS18048. The mutable property could change before the closure runs. Capture the checked value in const.
Practice and recap
Change the property after creating the callback and compare snapshot behavior.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mutation and closure caveats — 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 later(box:{text?:string}){ const text=box.text; if(text===undefined) return ()=>0; return ()=>text.length; }const box={text:"tea"}; const fn=later(box); box.text="x"; console.log(fn());Which diagnostic and explanation match the rejected example under the lesson settings?
function later(box:{text?:string}){ if(box.text===undefined) return ()=>0; return ()=>box.text.length; }