Keep Narrowed Types In Closures With const
Show why TypeScript resets narrowing on mutable let bindings inside callbacks, and preserve narrowed types by capturing a const snapshot before deferral.
Code
interface TokenSource {
current?: string;
}
function scheduleValidation(
source: TokenSource,
queue: Array<() => string>,
): void {
let token = source.current;
if (token === undefined) {
console.log('skipped: missing token');
return;
}
// Directly here, `token` is narrowed to `string`
console.log('immediate prefix:', token.slice(0, 4));
// Inside a closure, TypeScript widens `let token` back to `string | undefined`
// queue.push(() => token.toUpperCase()); // Compile error: 'token' is possibly 'undefined'
// Capture an immutable `const` snapshot so deferred closures keep `string`
const stableToken = token;
queue.push(() => `verified:${stableToken.toUpperCase()}`);
// Mutating the outer `let` proves why the closure needed its own `const` snapshot
token = undefined;
console.log('cleared outer let:', String(token));
}
const tasks: Array<() => string> = [];
scheduleValidation({ current: 'tok_alpha' }, tasks);
scheduleValidation({}, tasks);
for (const run of tasks) {
console.log('queued result:', run());
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
immediate prefix: tok_
cleared outer let: undefined
skipped: missing token
queued result: verified:TOK_ALPHAStep-by-step analysis — Keep Narrowed Types In Closures With const
Every runtime branch is contained inside function scheduleValidation.
A single loop drives the file — for (const run of tasks).
The input queue is mutated in place — callers that need the original must pass a copy.
Watch out for
- Zero external footprint: standard library primitives drive every behavior shown end to end.
queueis mutated in place — the value you pass will not be the same afterward.
Putting it to use
Entry signature: function scheduleValidation( source: TokenSource, queue: Array<()
The run prints skipped: missing token, immediate prefix:, cleared outer let: — each prefix names the step that produced it.
Core lines
queue.push(() => `verified:${stableToken.toUpperCase()}`);
const tasks: Array<() => string> = [];
Interactive Tools for This Topic
FAQ
- Does `scheduleValidation` modify its input?
- Yes — `queue` is mutated in place. Pass a copy if the caller needs the original preserved.
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `scheduleValidation` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.