Yuzhe's Blog

yuzhes

CartesianProduct

CartesianProduct

Problem Link

Problem

Given two sets (union types) T and U, return their Cartesian product as a union of tuples.

type T = CartesianProduct<1 | 2, 'a' | 'b'>
// [1, 'a'] | [1, 'b'] | [2, 'a'] | [2, 'b']

Solution

type CartesianProduct<T, U> =
  T extends T
    ? U extends U
      ? [T, U]
      : never
    : never

How it works:

  1. T extends T distributes the conditional type over each member of union T.
  2. Inside, U extends U distributes over each member of union U.
  3. For each combination (T, U), emit the tuple [T, U].
  4. The resulting union of all such tuples is the Cartesian product.

Key Takeaways