never 可以表示不可能发生的情况。never 用于永不返回的函数当一个函数永远不会成功返回(如抛出异常或进入无限循环),它的返回类型就是 never。
function throwError(message: string): never {
throw new Error(message);
}
throwError("This is an error!"); // 函数抛出异常,永远不会返回
解释:
throwError 函数抛出了一个异常,所以它永远不会正常返回。因此,其返回类型是 never。function infiniteLoop(): never {
while (true) {
console.log("This will run forever");
}
}
infiniteLoop(); // 函数进入无限循环,永远不会返回
解释:
infiniteLoop 函数进入了一个无限循环,因此它永远不会结束或返回任何值,所以返回类型是 never。never 用于不可能的类型在联合类型中,当通过类型缩小操作移除所有可能的类型时,剩下的类型就是 never。这通常用于类型检查的严格性。
nevertype Shape = 'circle' | 'square';
function getArea(shape: Shape): number {
if (shape === 'circle') {
return Math.PI * 1 * 1; // 假设圆的半径为1
} else if (shape === 'square') {
return 1 * 1; // 假设正方形的边长为1
} else {
const _exhaustiveCheck: never = shape;
throw new Error(`Unknown shape: ${_exhaustiveCheck}`);
}
}
解释:
getArea 函数处理 Shape 类型的参数,它可以是 'circle' 或 'square'。else 分支中的代码实际上永远不会执行,因为 shape 只能是 'circle' 或 'square'。因此,_exhaustiveCheck 变量的类型会被推断为 never,确保函数已经处理了所有可能的类型。Shape 类型新增了其他值(如 'triangle'),而 getArea 函数没有相应的处理逻辑,这段代码会在编译时报错,提醒开发者未处理新的情况。never 类型表示永远不会存在的值,常用于函数永远不会返回或类型缩小到不可能的情况。