2026-02-19 22:13:58
never 类型是 TypeScript 中表示永远不会发生的值的类型,用于描述函数抛出异常、无限循环或条件分支中不可能存在的值,是类型系统中的底部类型,可增强代码的类型安全性。
基本概念函数抛出异常或无限循环时的返回类型。
永远不可能为真的条件分支中的变量类型。
空集合的类型表示。
所有类型均可赋值给 never,但 never 只能赋值给自身。
例如:let x: never; let y: string = x; 会报错,因为 never 不能赋值给其他类型。
TypeScript 用 never 标记逻辑上不可达的代码。
示例:
function foo(x: string | number): boolean { if (typeof x === "string") return true; if (typeof x === "number") return false; // 此处的 x 被推断为 never,因为已覆盖所有可能情况 return error("Never happens");}穷尽性检查(Exhaustiveness Checking):
确保联合类型的所有分支均被处理,新增类型时未处理的分支会触发编译错误。
示例:
type Shape = "circle" | "square" | "triangle";function getArea(shape: Shape): number { switch (shape) { case "circle": return Math.PI * 2 * 2; case "square": return 4 * 4; case "triangle": return (3 * 4) / 2; default: const _exhaustiveCheck: never = shape; // 若 Shape 新增类型,此处报错 return _exhaustiveCheck; }}过滤联合类型:
利用条件类型从联合类型中排除特定类型。
示例:
type NonNullable<T> = T extends null | undefined ? never : T;type Foo = string | null | undefined;type Bar = NonNullable<Foo>; // 结果为 string函数永不返回:
标记函数通过抛出错误或无限循环终止执行,而非正常返回。
示例:
function fail(message: string): never { throw new Error(message);}不可能的条件分支:
在类型守卫中,未覆盖的分支会被推断为 never。
示例:
function fn(x: string | number) { if (typeof x === "string") { /* x 是 string */ } else if (typeof x === "number") { /* x 是 number */ } else { /* x 是 never */ }}构建复杂工具类型:
通过条件类型实现类型过滤或转换。
示例:
// 从 T 中移除 U 类型type Diff<T, U> = T extends U ? never : T;// 从 T 中移除 null 和 undefinedtype NotNullable<T> = Diff<T, null | undefined>;类型安全断言:
强制检查未覆盖的分支,确保类型安全。
示例:
function assertNever(x: never): never { throw new Error("Unexpected object: " + x);}function handleShape(shape: Shape) { switch (shape) { case "circle": /* ... */ break; case "square": /* ... */ break; default: assertNever(shape); // 若 shape 不是 never,报错 }}