TypeScript 中的 never 类型详解

高手们,我想请教下,TypeScript 中的 never 类型详解
最新回答
进不ㄋ怹

2026-02-19 22:13:58

never 类型是 TypeScript 中表示永远不会发生的值的类型,用于描述函数抛出异常、无限循环或条件分支中不可能存在的值,是类型系统中的底部类型,可增强代码的类型安全性。

基本概念
  • 定义:never 类型表示永远不会存在的值的类型,常见于以下场景:

    函数抛出异常或无限循环时的返回类型。

    永远不可能为真的条件分支中的变量类型。

    空集合的类型表示。

  • 示例:// 抛出错误的函数function error(message: string): never { throw new Error(message);}// 无限循环的函数function infiniteLoop(): never { while (true) {}}
特性
  • 底部类型:

    所有类型均可赋值给 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");}
常见使用场景
  1. 穷尽性检查(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; }}
  2. 过滤联合类型:

    利用条件类型从联合类型中排除特定类型。

    示例:

    type NonNullable<T> = T extends null | undefined ? never : T;type Foo = string | null | undefined;type Bar = NonNullable<Foo>; // 结果为 string
  3. 函数永不返回:

    标记函数通过抛出错误或无限循环终止执行,而非正常返回。

    示例:

    function fail(message: string): never { throw new Error(message);}
  4. 不可能的条件分支:

    在类型守卫中,未覆盖的分支会被推断为 never。

    示例:

    function fn(x: string | number) { if (typeof x === "string") { /* x 是 string */ } else if (typeof x === "number") { /* x 是 number */ } else { /* x 是 never */ }}
never vs void
  • void:函数正常执行完毕但无返回值。function noop(): void { return; }
  • never:函数永不正常返回(抛出错误或无限循环)。function fail(): never { throw new Error("Failed"); }
高级用法
  1. 构建复杂工具类型:

    通过条件类型实现类型过滤或转换。

    示例:

    // 从 T 中移除 U 类型type Diff<T, U> = T extends U ? never : T;// 从 T 中移除 null 和 undefinedtype NotNullable<T> = Diff<T, null | undefined>;
  2. 类型安全断言:

    强制检查未覆盖的分支,确保类型安全。

    示例:

    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,报错 }}
总结
  • 核心作用:never 类型通过标记不可能存在的值,增强代码的健壮性和类型安全性。
  • 典型场景:穷尽性检查、联合类型过滤、函数永不返回、不可达代码检测。
  • 与其他类型关系:作为底部类型,与 void、联合类型等结合实现高级类型操作。
  • 实践建议:在联合类型处理、工具类型构建中合理使用 never,可显著提升代码质量。