示例工程 08-unions-intersections
08-unions-intersections/02-discriminated-union/types.test-d.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;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 { Shape } from './src/main.js';
type Case1 = Expect<Equal<Shape['kind'], 'circle' | 'square' | 'rect'>>;
type Circle = Extract<Shape, { kind: 'circle' }>;
type Case2 = Expect<Equal<Circle, { kind: 'circle'; radius: number }>>;
// 收窄前不能访问分支独有属性
declare const shape: Shape;
// @ts-expect-error: Shape 上不保证有 radius
const bad: number = shape.radius;
export { bad };