Zip Types Pair Two Tuples Elementwise

Pair two tuples position by position with a recursive Zip type, and see how the result stops when one side runs out.

TypescriptData Integrity

Code

typescriptsnippet
29 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Putting it to use

Three runtime lines back the type-level claims — [ 'id', 1 ] [ 'name', 'ada' ] [ 'active', true ] for the full pairing, short length: 1 for the shorter side stopping early, empty pairs: 0 when one input is empty.

Output is labeled for readability — expect lines prefixed with short length:, empty pairs:.

Core lines under the microscope

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

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library.