In This Challenge, You should implement a type `Zip<T, U>`, T and U must be `Tuple` Learn tuple manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Zip type that pairs up corresponding elements from two tuples into a tuple of pairs, stopping at the length of the shorter tuple.
In This Challenge, You should implement a type Zip<T, U>, T and U must be Tuple
[object Object]Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<Zip<[], []>, []>>,
Expect<Equal<Zip<[1, 2], [true, false]>, [[1, true], [2, false]]>>,
Expect<Equal<Zip<[1, 2, 3], ['1', '2']>, [[1, '1'], [2, '2']]>>,
Expect<Equal<Zip<[], [1, 2, 3]>, []>>,
Expect<Equal<Zip<[[1, 2]], [3]>, [[[1, 2], 3]]>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Zip<T extends any[], U extends any[]> =
T extends [infer TFirst, ...infer TRest]
? U extends [infer UFirst, ...infer URest]
? [[TFirst, UFirst], ...Zip<TRest, URest>]
: []
: [];How it works:
T and U using nested conditional types with inferTFirst and UFirst are paired into [TFirst, UFirst], and the result is prepended to the recursive zip of the remaining elements TRest and URestT or U cannot be destructured), the recursion returns an empty tuple [], naturally handling tuples of different lengths by stopping at the shorter oneZip<[1, 2, 3], ['1', '2']> pairs 1 with '1' and 2 with '2', then stops because U is exhausted, producing [[1, '1'], [2, '2']]This challenge helps you understand parallel tuple traversal and recursive type pairing, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.