Yuzhe's Blog

yuzhes

Zip

Zip

Problem Link

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:

  1. Extract the head of both T and U.
  2. Pair them as [THead, UHead] and recurse on the tails.
  3. When either tuple is exhausted, return [] — zip stops at the shorter tuple.

Key Takeaways