never 是永远不会发生的值的类型——一个永远不返回的函数(抛出异常或无限循环)或编译器已证明不可能的分支。它是空类型:没有值可以分配给 never(除了 never 本身)。
ts
(): { (msg); }
(): { () {} }
never 是永远不会发生的值的类型——一个永远不返回的函数(抛出异常或无限循环)或编译器已证明不可能的分支。它是空类型:没有值可以分配给 never(除了 never 本身)。
(): { (msg); }
(): { () {} }
当您将联合类型缩小到无时,TypeScript 将剩余值的类型设为 never。您利用这一点来强制处理每种情况:
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "square": return s.side ** 2;
default:
// if all cases are handled, s is `never` here — assignment OK
const _exhaustive: never = s;
return _exhaustive;
}
}
现在,如果有人向 Shape 添加 { kind: "triangle"; ... } 但忘记了一个分支,default 中的 s 是三角形类型(不是 never),所以 const _exhaustive: never = s 编译失败 — 精确指出您需要更新的 switch 语句。
function a(): void {} // returns normally, just no value
function b(): never { throw "x"; } // never returns at all
never 将