在缩小范围时,您可以将联合的选项减少到您已删除所有可能性并且一无所有的程度。 在这些情况下,TypeScript 将使用 never 类型来表示不应该存在的状态。
never 类型可分配给每种类型; 但是,没有类型可以分配给 never(除了 never 本身)。 这意味着您可以使用缩小并依靠从不出现在 switch 语句中进行详尽的检查。
可以善用这一点进行错误处理。
例如,向我们的 getArea 函数添加一个默认值,该函数试图将形状分配为 never 在尚未处理所有可能的情况时引发。
interface Circle {kind: "circle";radius: number;}interface Square {kind: "square";sideLength: number;}type Shape = Circle | Square;function getArea(shape: Shape) {switch (shape.kind) {case "circle":return Math.PI * shape.radius ** 2;case "square":return shape.sideLength ** 2;default:const _exhaustiveCheck: never = shape;return _exhaustiveCheck;}}
如果我们在 shape 联合类型里增加一个新字段,比如:
interface Triangle {kind: "triangle";sideLength: number;}
会立即遇到语法错误: