问题库 JavaScript / TypeScript how-to

TypeScript 如何做类型收窄

快速答案

用 typeof、in、instanceof 或自定义类型守卫缩小联合类型。

js
function isUser(value: unknown): value is { id: string } {
  return typeof value === 'object' && value !== null && 'id' in value;
}

使用要点

  • TypeScript 只在编译期提供保护,接口返回值仍要做运行时校验。
  • 类型收窄写清楚以后,再把数据交给业务函数,减少后续的断言。

相关内容