示例工程 02-basic-types-inference

02-basic-types-inference/02-tuple-vs-array/types.test-d.ts

typescript · 0.6 KB

运行:02 · tuple-vs-array

点击「运行示例」后,左侧显示源码、右侧显示运行结果;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 { Point, LogEntry } from './src/main.js';
 
type Case1 = Expect<Equal<Point, [x: number, y: number]>>;
type Case2 = Expect<Equal<LogEntry[0], 'info' | 'warn'>>;
type Case3 = Expect<Equal<LogEntry[1], string>>;
 
// 元组长度固定为 2
// @ts-expect-error: 三元组不能赋给二元组
const tooLong: Point = [1, 2, 3];
 
// 位置类型必须匹配
// @ts-expect-error: 第二个元素必须是 number
const wrongType: Point = [1, '2'];
 
export { tooLong, wrongType };