示例工程 12-variance-soundness

12-variance-soundness/01-array-covariance/types.test-d.ts

typescript · 0.5 KB

运行:12 · array-covariance

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

type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
 
import type { Animal, Dog } from './src/main.js';
 
// 数组是协变的:Dog[] 可赋给 Animal[]
type Case1 = Expect<Equal<Dog[] extends Animal[] ? true : false, true>>;
 
// 但写入后类型不再可信:Animal[] 里可能有非 Dog
declare const animals: Animal[];
// @ts-expect-error: Animal 没有 bark,说明元素类型已被拓宽
const bark = animals[0]?.bark();
 
export { bark };