← 中文资源

简体中文版本

Map.get 通过局部变量收窄而非 has

先查 map.has(key) 在 TypeScript 里并不能收窄随后的 map.get(key);改用局部变量接住返回值并判空,免去非空断言即可安全读取。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

hit: u-10(admin)
miss: missing:tok-9
inserted: u-22 size: 2

实现说明

全部逻辑都在函数 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);