Zip
Less than 1 minuteTC-Medium
Zip
Problem
In This Challenge, You should implement a type Zip<T, U>, T and U must be Tuple.
type exp = Zip<[1, 2], [true, false]> // expected to be [[1, true], [2, false]]Solution
Approach: Parallel Tuple Destructuring
Peel one element from each tuple simultaneously and pair them up.
type Zip<T extends unknown[], U extends unknown[]> =
T extends [infer THead, ...infer TTail]
? U extends [infer UHead, ...infer UTail]
? [[THead, UHead], ...Zip<TTail, UTail>]
: []
: []How it works:
- Extract the head of both
TandU. - Pair them as
[THead, UHead]and recurse on the tails. - When either tuple is exhausted, return
[]— zip stops at the shorter tuple.
Key Takeaways
- Nested
extendsdestructuring on two tuples simultaneously is idiomatic for zip-style operations. - The result length equals
min(T['length'], U['length'])— standard zip semantics.
