# 12 · 类型兼容性、型变与健全性

> 学完这章，你能解释为什么 `Dog[]` 可以赋给 `Animal[]`、为什么函数参数要反过来检查，以及 TypeScript 为什么故意保留一些不安全的漏洞。

## 本章目标

- [ ] 能区分协变、逆变、双变与不变，并在数组、函数、只读类型上各举一例
- [ ] 能解释 `strictFunctionTypes` 只对函数属性生效、对方法无效的原因
- [ ] 能说出数组协变与 `any` 造成的不健全（unsoundness）
- [ ] 能用 `in` / `out` 标注类型参数的型变
- [ ] 能判断一处「类型检查通过」是否真的意味着运行时安全

## 前置知识

- 第 04 章（结构化类型）
- 第 05 章（函数类型）、第 07 章（类）

## 从你熟悉的语言出发

| 你熟悉的 | 型变规则 | TypeScript 的对应 | 关键差异 |
| --- | --- | --- | --- |
| Java 泛型 | `? extends T` 协变、`? super T` 逆变，使用时声明 | 调用点自动推断 + `in`/`out` 声明点标注 | TS 默认按结构推断，标注是可选的检查加强 |
| C++ `const` | `const T&` 可接受非 const | `readonly` 协变 | TS 的 `readonly` 只在类型层，浅层 |
| C# `in`/`out` | 声明点型变，运行时泛化 | `in`/`out` 类型参数 | TS 只做静态检查，运行时擦除 |
| Go | 无泛型型变（接口靠方法集） | 结构化 + 型变 | Go 接口更接近「行为子类型」 |

一句话：**TS 的型变是结构化可赋值性的副产品，不是一套显式的继承规则。**

## 正文

### 12.1 可赋值性是核心

TypeScript 没有「子类型声明」，只有「A 能否赋给 B」。型变描述的就是：当 `A` 是 `B` 的子类型时，`Box<A>` 与 `Box<B>` 的关系。

```ts
type Animal = { name: string };
type Dog = Animal & { bark(): void };

declare const dog: Dog;
const animal: Animal = dog; // Dog 是 Animal 的子类型（结构上更具体）
```

`Dog` 比 `Animal` 多一个 `bark`，所以 `Dog` 可赋给 `Animal`。这叫「子类型方向更具体」。

### 12.2 协变：容器跟着子类型走

```ts
declare const dogs: Dog[];
const animals: Animal[] = dogs; // 合法
```

`Dog[]` 可赋给 `Animal[]`，这就是协变。它符合直觉：每只狗都是动物，所以狗数组也是动物数组。

但数组是可写的，协变会破坏类型安全（见 12.4）。

只读容器是安全的协变：

```ts
declare const dogs: readonly Dog[];
const animals: readonly Animal[] = dogs; // 安全
```

因为 `readonly` 阻止了写入，协变不会引入「往狗数组里塞猫」的可能。

### 12.3 逆变：函数参数反过来

```ts
type AnimalHandler = (animal: Animal) => void;
type DogHandler = (dog: Dog) => void;

declare const animalHandler: AnimalHandler;
declare const dogHandler: DogHandler;

const a: DogHandler = animalHandler; // 合法
const b: AnimalHandler = dogHandler; // error
```

为什么？调用 `a(dog)` 时，`animalHandler` 只要求 `Animal`，`Dog` 满足它，安全。而 `b(animal)` 时，`dogHandler` 要求 `Dog`，`Animal` 不满足，运行时会崩。

`strictFunctionTypes: true` 打开后，函数**属性**按逆变检查。基线已开启。

### 12.4 方法双变：历史兼容的例外

```ts
interface MethodBox {
  set(value: Animal): void;
}

interface FunctionBox {
  set: (value: Animal) => void;
}

const method: MethodBox = { set(value: Dog) {} };   // 合法
const fn: FunctionBox = { set(value: Dog) {} };     // error
```

方法声明（`set(value: Animal): void`）的参数是**双变**的：两个方向都接受。这是为了兼容 `Array.prototype.push`、`sort` 等既有 API 的写法；如果强制逆变，大量老代码会立刻报错。

这也是 `strictFunctionTypes` 的一个盲区：把方法改写成函数属性，检查立刻变严。

### 12.5 不健全：数组与 `any`

**数组协变**：

```ts
function pushAnimal(list: Animal[]): void {
  list.push({ name: 'cat' });
}

const dogs: Dog[] = [{ name: 'Rex', bark: () => {} }];
pushAnimal(dogs); // 合法
dogs[1].bark();   // 运行时 TypeError：cat 没有 bark
```

`dogs` 的类型仍是 `Dog[]`，但里面已经混进了 `Animal`。这是 TS 最著名的不健全之一，官方明确保留：完全修掉需要让数组不变（invariant），会破坏海量代码。

**`any`**：

```ts
const value: any = 1;
const dog: Dog = value; // 合法，运行时 dog 是 number
```

`any` 同时是 top 和 bottom：任何类型都能赋给它，它也能赋给任何类型。这是「逃生舱」的代价，所以基线默认禁用 `any`（第 16 章讲治理）。

### 12.6 `in` / `out` 型变标注

TS 4.7 起可以在类型参数上声明型变：

```ts
interface Producer<out T> {
  get(): T;
}

interface Consumer<in T> {
  accept(value: T): void;
}

interface Box<in out T> {
  get(): T;
  set(value: T): void;
}
```

- `out T`：`T` 只能出现在输出位置，`Producer<Dog>` 可赋给 `Producer<Animal>`。
- `in T`：`T` 只能出现在输入位置，`Consumer<Animal>` 可赋给 `Consumer<Dog>`。
- `in out T`：两个方向都出现，不变。

标注不是必需的：编译器本来就会推断。写出来的价值是**更早暴露错误**——如果 `out T` 出现在参数位置，立刻报 `TS2636`，而不是等到某个赋值处才发现。

## 类型错误现场

**场景一：函数参数逆变失败**。`examples/12-variance-soundness/02-function-variance/demo/narrow-param.ts`：

```ts
handleAnimal(dogHandler);
```

真实报错（TypeScript 7.0.2）：

```text
demo/narrow-param.ts(14,14): error TS2345: Argument of type '(dog: Dog) => void' is not assignable to parameter of type '(animal: Animal) => void'.
  Types of parameters 'dog' and 'animal' are incompatible.
    Type 'Animal' is not assignable to type 'Dog'.
      Property 'bark' is missing in type 'Animal' but required in type '{ bark(): void; }'.
```

- `TS2345` 表示实参不可赋给形参。
- 根因在参数逆变：目标函数接收任意 `Animal`，而 `dogHandler` 只保证处理 `Dog`。
- 修复：把回调参数放宽到 `Animal`，或在调用前收窄。

**场景二：型变标注与使用位置冲突**。`examples/12-variance-soundness/04-variance-annotations/demo/wrong-variance.ts`：

```ts
interface Broken<out T> {
  read(): T;
  write: (value: T) => void;
}
```

真实报错：

```text
demo/wrong-variance.ts(3,18): error TS2636: Type 'Broken<sub-T>' is not assignable to type 'Broken<super-T>' as implied by variance annotation.
  Types of property 'write' are incompatible.
    Type '(value: sub-T) => void' is not assignable to type '(value: super-T) => void'.
```

- `TS2636` 是型变标注专属错误：声明的型变与实际使用不一致。
- 修复：把 `out T` 改成 `in out T`，或把 `write` 移出该接口。

## 反直觉差异：TypeScript 故意不健全

**你的直觉**：有静态类型检查的语言应该保证「类型正确 ⇒ 运行时不会出现类型错误」。Java 的数组协变会抛 `ArrayStoreException`，C# 会在运行时检查。

**实际行为**：TypeScript 明确接受不健全（unsoundness），并且不打算完全修复：

```ts
const dogs: Dog[] = [{ name: 'Rex', bark: () => {} }];
const animals: Animal[] = dogs;
animals.push({ name: 'cat' }); // 合法
dogs[1].bark();                 // TypeError
```

类似漏洞还有：`any`、索引签名、`Object.keys` 的字符串数组、可选属性与 `undefined`、`as` 断言。

**为什么这样设计**：TypeScript 的首要目标是「给现有 JavaScript 加类型」，而不是「证明程序正确」。完全健全需要：

- 数组不变 → `push`/`sort` 等 API 大量报错；
- 索引签名精确建模 → 动态对象的写法全部变复杂；
- 运行时类型检查 → 产物变大、性能下降、与 JS 语义冲突。

这些代价会劝退绝大多数现有项目。TS 团队选择「在常见写法上足够安全，在边缘保留逃生舱」，并用 `strict` 系列选项逐步收紧。

**正确写法**：

- 边界数据：运行时校验（第 32 章）。
- 对外 API：尽量用 `readonly` 数组、`unknown` 而不是 `any`。
- 类型断言：只在确实知道真相时用，并写注释说明依据。
- 不要把「编译通过」当成「运行时安全」的证据。

## 示例索引

| 目录 | 演示什么 | 预期看到 |
| --- | --- | --- |
| `examples/12-variance-soundness/01-array-covariance/` | 数组协变漏洞 | `length:2`、`isDog:false` |
| `examples/12-variance-soundness/02-function-variance/` | 函数参数逆变 | `animal:...`、`handled`；失败配置贴 `TS2345` |
| `examples/12-variance-soundness/03-method-bivariance/` | 方法双变 vs 函数属性 | `method:ok`；失败配置贴 `TS2322` |
| `examples/12-variance-soundness/04-variance-annotations/` | `in`/`out` 标注 | `producer:Rex`、`consumer:ok`；失败配置贴 `TS2636` |

## 练习题

1. 把 `examples/12-variance-soundness/01-array-covariance/src/main.ts` 的 `pushAnimal` 参数改成 `readonly Animal[]`，观察 `dogs` 是否还能传入，并解释原因。
2. 给 `examples/12-variance-soundness/02-function-variance/src/main.ts` 增加一个返回 `Dog` 的回调，验证返回类型是协变的（`() => Dog` 可赋给 `() => Animal`）。
3. 把 `examples/12-variance-soundness/04-variance-annotations/src/main.ts` 的 `Box` 拆成 `ReadOnlyBox<out T>` 与 `WriteOnlyBox<in T>`，并让类型测试断言两个方向的赋值。

<details><summary>参考答案</summary>

1. 可以传入：`Dog[]` 可赋给 `readonly Animal[]`（协变且只读安全）。但 `pushAnimal` 内部不能再 `push`，因为 `readonly` 数组没有 `push` 方法。这正好说明「只读 + 协变」是安全的组合。

2. ```ts
   type AnimalFactory = () => Animal;
   const dogFactory = (): Dog => ({ name: 'Rex', bark: () => {} });
   const animalFactory: AnimalFactory = dogFactory; // 合法
   ```
   返回类型协变：更具体的返回值可以赋给更宽的返回类型。

3. ```ts
   interface ReadOnlyBox<out T> { get(): T }
   interface WriteOnlyBox<in T> { set(value: T): void }
   ```
   类型测试断言 `ReadOnlyBox<Dog> extends ReadOnlyBox<Animal>` 与 `WriteOnlyBox<Animal> extends WriteOnlyBox<Dog>`。

</details>

## 章末自检

1. 协变、逆变、双变各是什么意思？
2. 为什么 `Dog[]` 可赋给 `Animal[]`？这安全吗？
3. `strictFunctionTypes` 对方法和函数属性的处理一样吗？
4. `in` / `out` 标注会改变运行时吗？
5. `any` 为什么同时是 top 和 bottom？
6. 举出两个 TS 故意保留的不健全。

<details><summary>参考答案</summary>

1. 协变：容器方向与元素一致；逆变：方向相反；双变：两个方向都接受。
2. 因为 `Dog` 是 `Animal` 的子类型，数组按协变处理；不安全，写入 `Animal` 后原数组混入非 `Dog`。
3. 不一样。函数属性按逆变检查，方法参数双变。
4. 不会，只影响检查；运行时类型擦除。
5. 任何类型都能赋给 `any`（top），`any` 也能赋给任何类型（bottom）。
6. 数组协变、`any` 的任意赋值；还有索引签名与 `as` 断言等。

</details>

## 延伸阅读

- TypeScript Handbook：*Type Compatibility*（型变、双变、可赋值性）
- TypeScript 4.7 Release Notes：*Optional Variance Annotations for Type Parameters*
- TypeScript 2.6 Release Notes：*Strict Function Types*
- TypeScript FAQ：*Why are arrays covariant?*、*What is soundness?*
