类型系统基础第 8 章预计 15 分钟
本章示例(4 个,可直接运行)

示例在隔离的 iframe 中执行,console 输出会显示在运行面板里;源码与测试文件可在源码页查看。

08 · union-basics

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

08 · discriminated-union

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

08 · intersection

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

08 · state-machine

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

本页目录(16 节)

08 · 联合、交叉与可辨识联合

学完这章,你能把「可能是 A 也可能是 B」和「同时是 A 和 B」写成类型,并用可辨识联合把状态机、事件、结果类型表达得既安全又可穷尽。

本章目标

  • 能写联合与交叉,并说清 A | B 的可用操作为什么受限于公共成员
  • 能设计可辨识联合(标签字段 + 字面量类型),并用 switch 逐分支收窄
  • 能解释原始类型交叉为什么得到 never,以及对象交叉为什么合并属性
  • 能用 never 做穷尽检查,把「漏分支」变成编译错误
  • 能用一个 State + Event → State 的 reducer 建模状态机

前置知识

  • 第 03 章(收窄、never)
  • 第 04 章(对象类型)、第 07 章(类)

从你熟悉的语言出发

你熟悉的 表达方式 TypeScript 的对应 关键差异
C union + tag 手工维护 tag 字段 可辨识联合 tag 是类型的一部分,漏分支会报错
C++ std::variant visit + 类型列表 联合 + switch TS 不要求预先列出访问器
Java sealed interface permits + 模式匹配 可辨识联合 TS 的封闭性靠联合本身,不靠关键字
Go type switch 接口 + case T: typeof / in / 谓词 TS 的分支不新建变量
Rust enum 每个变体带数据 可辨识联合 Rust 编译器强制穷尽;TS 靠 never 兜底

一句话:联合表达「之一」,交叉表达「同时」,可辨识联合让两者都能被编译器穷尽检查。

正文

8.1 联合:值属于其中之一

type Id = string | number;
 
function toKey(id: Id): string {
  return typeof id === 'string' ? id : id.toString();
}

联合的关键限制是:只能使用所有成员共有的操作。

type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number };
 
declare const shape: Shape;
shape.radius; // error TS2339:square 上没有 radius

要访问分支独有属性,必须先收窄(第 03 章)。联合不是「所有属性的并集」,而是「值可能是其中之一」。

8.2 交叉:值同时满足

type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
 
const person: Person = { name: 'Ada', age: 36 };

对象交叉会合并属性;原始类型交叉则没有值能同时满足:

type Impossible = string & number; // never

交叉常用于「给已有类型加约束」:

type WithId<T> = T & { id: string };

它不会复制运行时字段,只是类型层的「且」。

8.3 可辨识联合:给每个分支一个标签

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };
 
function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.side ** 2;
    default:
      return assertNever(shape);
  }
}

三个条件缺一不可:

  1. 每个分支都有一个同名字段(这里 kind)。
  2. 该字段的类型是字面量('circle' 而不是 string)。
  3. 所有分支的字面量互不相同。

满足后,switch (shape.kind) 的每个 case 都能把 shape 收窄到对应分支。若把 kind 写成 string,收窄失效,shape.radius 立即报错。

8.4 never 与穷尽检查

function assertNever(value: never): never {
  throw new Error(`unreachable: ${JSON.stringify(value)}`);
}

当所有分支都处理完,default 里的 shape 被收窄为 never,assertNever(shape) 合法。将来给联合加成员,shape 在该分支不再是 never,TS2345 立刻出现。

这把「运行时才发现的漏分支」提前到了编译期。never 还可以表示「永不返回」:

function fail(message: string): never {
  throw new Error(message);
}

8.5 用联合建模状态机

type State =
  | { status: 'idle' }
  | { status: 'loading'; requestId: number }
  | { status: 'success'; data: readonly string[] }
  | { status: 'error'; message: string };
 
type Event =
  | { type: 'fetch'; requestId: number }
  | { type: 'resolve'; data: string[] }
  | { type: 'reject'; message: string }
  | { type: 'reset' };
 
function reduce(state: State, event: Event): State {
  switch (event.type) {
    case 'fetch':
      return { status: 'loading', requestId: event.requestId };
    case 'resolve':
      return state.status === 'loading' ? { status: 'success', data: event.data } : state;
    case 'reject':
      return state.status === 'loading' ? { status: 'error', message: event.message } : state;
    case 'reset':
      return { status: 'idle' };
    default:
      return assertNever(event);
  }
}

好处:

  • 非法状态无法构造:{ status: 'success' } 缺少 data,直接报错。
  • 非法事件被忽略:idle 状态收到 resolve 时保持原状态,而不是抛异常或写入半成品。
  • 事件与状态都是可穷尽的:加一个 cancel 事件,所有 switch 都会提示补分支。

8.6 联合上的多余属性检查更宽松

第 04 章讲过新鲜字面量的多余属性检查。联合类型有一个例外:只要字面量匹配任意一个分支,额外属性不会报错。

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };
 
const shape: Shape = { kind: 'circle', radius: 1, extra: true }; // 合法

原因是检查器无法确定你指的是哪个分支,只能按「至少匹配一个」处理。这会让拼写错误更难发现,所以可辨识联合的标签字段命名要稳定,必要时用 satisfies 或运行时校验兜底。

类型错误现场

场景一:值不在联合里。examples/08-unions-intersections/01-union-basics/demo/not-in-union.ts:

type Id = string | number;
const id: Id = true;

真实报错(TypeScript 7.0.2):

demo/not-in-union.ts(5,7): error TS2322: Type 'boolean' is not assignable to type 'Id'.
  • TS2322 是最常见的「不可赋值」。
  • 修复:把 true 改成字符串/数字,或把 boolean 加进联合(如果契约确实需要)。

场景二:漏掉事件分支。examples/08-unions-intersections/04-state-machine/demo/not-exhaustive.ts:

type Event = { type: 'fetch' } | { type: 'reset' } | { type: 'cancel' };
// switch 只处理 fetch / reset

真实报错:

demo/not-exhaustive.ts(19,26): error TS2345: Argument of type '{ type: "cancel"; }' is not assignable to parameter of type 'never'.
  • TS2345 在这里不是「参数类型不匹配」的普通场景,而是穷尽检查失败:assertNever 只接受 never,而 cancel 还没被处理。
  • 修复:补上 case 'cancel',或把 cancel 从联合里删掉(如果它不该存在)。

反直觉差异:A | B 在运行时没有任何标签

你的直觉:C 的 union 有 tag,Rust 的 enum 有判别字段;TS 的联合应该也在运行时保留「当前是哪个分支」。

实际行为:联合完全是类型层的,运行时只剩值本身:

type Id = string | number;
const id: Id = 1;
 
typeof id; // 'number'
Object.keys(id as object); // 对原始类型无意义

即使是可辨识联合,kind 字段也是你自己写进对象里的普通属性,不是编译器注入的标签:

const shape: Shape = { kind: 'circle', radius: 1 };
shape.kind; // 'circle'

编译器不会阻止你在运行时把 kind 改成别的值(通过 as 或外部数据),也不会在值上附加隐藏字段。

为什么这样设计:TS 的产物必须是普通 JavaScript,不能引入额外的运行时表示。联合的「标签」必须由数据本身携带,这也是可辨识联合要求你自己写 kind 的原因。好处是零成本、可与 JSON 直接互操作;代价是运行时校验必须自己做。

正确写法:

  • 设计可辨识联合时,标签字段用字面量,且不要复用会变化的值。
  • 外部数据进入时,先校验 kind 再收窄(第 32 章)。
  • 不要依赖 instanceof 判断联合分支,原始类型没有构造器。

示例索引

目录 演示什么 预期看到
examples/08-unions-intersections/01-union-basics/ 联合与 Maybe<T> 5 行输出;失败配置贴 TS2322
examples/08-unions-intersections/02-discriminated-union/ 可辨识联合与 never 3.14、9、10;失败配置贴 TS2339
examples/08-unions-intersections/03-intersection/ 交叉类型与 never Ada:36、admin:3;失败配置贴 TS2322
examples/08-unions-intersections/04-state-machine/ 状态机 reducer loading、success、idle、loading、error;失败配置贴 TS2345

练习题

  1. 给 examples/08-unions-intersections/01-union-basics/src/main.ts 增加 type Nullable<T> = T | null | undefined,并写一个 unwrap 函数,要求用 ?? 之外的方式处理 undefined。
  2. 把 examples/08-unions-intersections/02-discriminated-union/src/main.ts 的 Shape 改成 { kind: 'rect'; width: number; height: number } 与 { kind: 'square'; side: number } 两个分支,观察 area 的 switch 是否仍能穷尽。
  3. 在 examples/08-unions-intersections/04-state-machine/src/main.ts 增加 { type: 'cancel' } 事件与 { status: 'cancelled' } 状态,要求所有 switch 都补分支。
  1. type Nullable<T> = T | null | undefined;
    function unwrap<T>(value: Nullable<T>, fallback: T): T {
      return value === null || value === undefined ? fallback : value;
    }

    不能用 ?? 之外的方式时,显式比较即可;?? 只处理 null/undefined,与这里等价。

  2. 仍能穷尽,但 rect 需要 width 与 height 两个字段;square 与 rect 的 kind 不同,switch 各一个分支,default 仍是 never。

  3. State 增加 { status: 'cancelled' },Event 增加 { type: 'cancel' };reduce 的 cancel 分支返回 cancelled,reset 可从任意状态回到 idle。所有 switch 补完后,assertNever 才继续成立。

章末自检

  1. A | B 上能直接访问 A 独有的属性吗?为什么?
  2. 对象交叉与原始类型交叉的结果分别是什么?
  3. 可辨识联合的三个必要条件是什么?
  4. assertNever 为什么能发现漏分支?
  5. 联合上的多余属性检查为什么比单一对象宽松?
  6. 可辨识联合的 kind 是编译器注入的吗?
  1. 不能。联合的每个成员都必须有该属性才安全;否则运行时可能是另一个分支。
  2. 对象交叉合并属性;原始类型交叉得到 never。
  3. 同名标签字段、字面量类型、字面量互不相同。
  4. 所有分支处理完后剩余类型是 never;漏掉的分支会让参数不再是 never,触发 TS2345。
  5. 检查器无法确定字面量匹配哪个分支,只要求至少匹配一个,因此不检查额外属性。
  6. 不是。kind 是普通属性,由你写入数据;运行时没有隐藏标签。

延伸阅读

  • TypeScript Handbook:Narrowing 中「Discriminated unions」小节
  • TypeScript Handbook:Everyday Types 中「Union Types」「Intersection Types」
  • Java Language Specification §9.1.4 Sealed Classes and Interfaces(对照封闭联合)
  • Rust Book:Enums and Pattern Matching(对照穷尽匹配)