Map.get Narrows Through A Local Binding
Narrow Map values safely by assigning map.get(key) to a local binding instead of calling map.has(key) first, avoiding non-null assertions in strict TypeScript.
Code
interface Session {
userId: string;
role: 'member' | 'admin';
}
const sessions = new Map<string, Session>([
['tok-1', { userId: 'u-10', role: 'admin' }],
]);
// Calling `sessions.has(id)` does NOT narrow a subsequent `sessions.get(id)`.
// Bind the lookup result once so control-flow analysis narrows `Session | undefined`.
function describeSession(id: string): string {
const hit = sessions.get(id);
if (hit === undefined) {
return `missing:${id}`;
}
return `${hit.userId}(${hit.role})`;
}
function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
const existing = map.get(key);
if (existing !== undefined) {
return existing;
}
const created = create();
map.set(key, created);
return created;
}
console.log('hit:', describeSession('tok-1'));
console.log('miss:', describeSession('tok-9'));
const inserted = getOrCreate(sessions, 'tok-2', () => ({ userId: 'u-22', role: 'member' }));
console.log('inserted:', inserted.userId, 'size:', sessions.size);Output
Captured from a sandboxed run of this snippet in the build pipeline.
hit: u-10(admin)
miss: missing:tok-9
inserted: u-22 size: 2Implementation flow — Map.get Narrows Through A Local Binding
Map.get Narrows Through A Local Binding is built around the functions describeSession and getOrCreate.
Caveats
- Constructed without third-party crates so neither registry nor lockfile changes.
- The guard
hit === undefinedbails out immediately through an upstreamreturnwhen its condition holds.
Applying it
The entry-point signature is function describeSession(id: string)
Output lines are prefixed (hit:, miss:, inserted:), keeping runtime milestones transparent throughout stdout lines.
Statements that matter
const inserted = getOrCreate(sessions, 'tok-2', () => ({ userId: 'u-22', role: 'member' }));
function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
const existing = map.get(key);
if (existing !== undefined) {
return existing;
}
const created = create();
map.set(key, created);
return created;
}
return `${hit.userId}(${hit.role})`;
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `describeSession`, `getOrCreate` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.