使用要点
- 直接运行文件,输出会带上标签,比如
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);