← 中文资源

简体中文版本

Zip 类型逐元素配对两个元组

用变长元组类型实现 Zip,把两个元组按位置配对,并在长度不足时停止。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[ 'id', 1 ] [ 'name', 'ada' ] [ 'active', true ]
short length: 1
empty pairs: 0

使用要点

  • 直接运行文件,输出会带上标签,比如 short length:、empty pairs:——输出的每一行都能指回产生它的那次调用。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。

核心语句

? B extends readonly [infer HeadB, ...infer TailB extends readonly unknown[]]
  ? [[HeadA, HeadB], ...Zip<TailA, TailB>]
  : []
: [];

代码示例

type Zip<A extends readonly unknown[], B extends readonly unknown[]> = A extends readonly [
  infer HeadA,
  ...infer TailA extends readonly unknown[],
]
  ? B extends readonly [infer HeadB, ...infer TailB extends readonly unknown[]]
    ? [[HeadA, HeadB], ...Zip<TailA, TailB>]
    : []
  : [];

type Left = ['id', 'name', 'active'];
type Right = [number, string, boolean];
type Rows = Zip<Left, Right>;

const idRow: Rows[0] = ['id', 1];
const nameRow: Rows[1] = ['name', 'ada'];
const activeRow: Rows[2] = ['active', true];
console.log(idRow, nameRow, activeRow);

// Shorter side stops the elementwise pairing early
type Short = Zip<['a'], [1, 2]>;
const short: Short = [['a', 1]];
console.log('short length:', short.length);

// 类型不匹配的配对无法通过编译
// const wrong: Rows[0] = ['id', 'one'];

type OnlyA = Zip<['a', 'b'], []>;
const empty: OnlyA = [];
console.log('empty pairs:', empty.length);