从不类型
一句话解释
从不类型 represents 值那个从不 occurs — 否值 能有 类型从不. 它是 used for 函数那个总是 throw and for exhaustiveness 检查.
用大白话说
never 类型平均值 "这个能从不 happen." 否值 能有 类型 never. It is used for functions that always throw an error or have infinite loops (they never return), and for exhaustiveness checking.
In exhaustiveness checking, if you handle all cases of a union in a switch, the default branch has type 从不. If you later add a new case to the union, the default branch is no longer 从不, and TypeScript errors — forcing you to handle the new case.
从不 is the bottom type: it is assignable to every type, but no type is assignable to it (except never itself). It is also the result of impossible intersections like 字符串 & 数字.
示例
function throwError(msg: string): never {
throw new Error(msg); // never returns
}
// Exhaustiveness checking
type Shape = "circle" | "square";
function area(s: Shape): number {
switch (s) {
case "circle": return Math.PI;
case "square": return 1;
default: const _exhaustive: never = s; return _exhaustive;
}
}throwError 返回从不. 默认情况 uses 从不 for exhaustiveness 检查.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。