Skip to content

可辨识联合穷尽性检查失败

快速摘要

你的 switch 语句缺少某个联合成员的情况 —— 通过 'default: assertNever' 的穷尽性检查捕获它。

为什么发生

  • 可辨识联合添加了新变体但 switch 未更新

  • 某个 case 中判别属性名拼写错误,导致不匹配

  • 穷尽性检查函数(assertNever)缺失或未在 default case 中调用

最小示例

✗ 错误代码
type Action = { type: 'start' } | { type: 'stop' } | { type: 'pause' };
function handle(action: Action) {
  switch (action.type) {
    case 'start': return 1;
    case 'stop': return 2;
    // missing 'pause' case!
  }
}
✓ 修复代码
type Action = { type: 'start' } | { type: 'stop' } | { type: 'pause' };
function assertNever(x: never): never { throw new Error(); }
function handle(action: Action) {
  switch (action.type) {
    case 'start': return 1;
    case 'stop': return 2;
    case 'pause': return 3;
    default: return assertNever(action); // compile error if missing case
  }
}

default case 中的 assertNever 函数使 TypeScript 在缺少联合变体处理时在编译时报错。

如何诊断

  • 检查联合类型定义的所有变体并与 switch case 比较

  • 在 default case 中使用 assertNever 函数获取缺失 case 的编译错误

  • 悬停 switch 中的判别属性查看其类型和所有可能值

如何修复

  • 为新的联合变体添加缺失的 case

  • 修正 case 子句中判别属性名的拼写

  • 在 default case 中添加 assertNever(x: never) 函数调用以在编译时强制穷尽性

如何预防

  • 始终在可辨识联合 switch 的 default case 中使用 assertNever 穷尽性检查

  • 添加新联合变体时,编译器会对所有非穷尽 switch 报错

相关资源

相关术语

相关课程

← 返回语言