示例工程 12-variance-soundness

12-variance-soundness/04-variance-annotations/README.md

markdown · 1.1 KB

运行:12 · variance-annotations

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

# 04 · variance-annotations
 
**演示**:`out` 标注协变、`in` 标注逆变、`in out` 标注不变;编译器据此提前发现型变错误。
**运行**:在 `tutorials/typescript` 下执行 `npm run build`,再执行 `npm run serve`,打开
`http://localhost:8080/examples/12-variance-soundness/04-variance-annotations/`;开 Console。
**预期控制台输出**:
```text
producer:Rex
consumer:ok
```
**类型检查**:`node node_modules/typescript/bin/tsc -p examples/12-variance-soundness/04-variance-annotations/tsconfig.types.json`
**预期类型错误**(`demo/wrong-variance.ts`,由 `tsconfig.fail.json` 触发):
```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'.
```
**注意**:`in`/`out` 只对类型参数做约束检查,不改变运行时;不写也能推断出型变,写出来是为了让错误更早暴露。