Skip to content
TypeScript·Advanced·Coding·1 min read

Why can narrowing be lost across a callback?

Short interview answer

The callback may run later after a mutable property or captured binding changes, so TypeScript cannot always preserve earlier evidence. Copy the narrowed value to a const or redesign the data so mutation cannot invalidate the assumption.

Example

TypeScript
if (obj.value !== null) {  setTimeout(() => obj.value.toUpperCase()); // Error — value may be null by now}
const v = obj.value;if (v !== null) {  setTimeout(() => v.toUpperCase()); // ok — const can't change}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Type narrowing

Related questions