示例工程 03-literal-types-narrowing
03-literal-types-narrowing/01-literal-widening/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 { Direction, literal, widened, fixed, current } from './src/main.js';
type Case1 = Expect<Equal<typeof literal, 'up'>>;
type Case2 = Expect<Equal<typeof widened, string>>;
type Case3 = Expect<Equal<typeof fixed, 'up'>>;
type Case4 = Expect<Equal<typeof current, Direction>>;
// widened 已经变成 string,不能再直接赋给 Direction
// @ts-expect-error: string 不能赋给字面量联合
const assigned: Direction = widened;
// 标注后非法值被拒绝
// @ts-expect-error: north 不在 Direction 中
const invalid: Direction = 'north';
export { assigned, invalid };