实现说明
全部逻辑都在函数 describeSession、getOrCreate中。
使用要点
- 导入(如果有的话)只指向标准库模块。
- 守卫
hit === undefined一旦成立就走提前的return,把后续流程挡掉。 - 跑完文件,输出里会留下标记——
hit:、miss:、inserted:。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 describeSession、getOrCreate。
签名一览:function describeSession(id: string)
核心语句
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})`;
代码示例
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);