CartesianProduct
Less than 1 minuteTC-Medium
CartesianProduct
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
: neverHow it works:
T extends Tdistributes the conditional type over each member of unionT.- Inside,
U extends Udistributes over each member of unionU. - For each combination
(T, U), emit the tuple[T, U]. - The resulting union of all such tuples is the Cartesian product.
Key Takeaways
- Double distribution over two unions (
T extends T ? U extends U ? ...) is the idiomatic way to compute a Cartesian product in TypeScript's type system. - The expression
T extends Tlooks trivially true, but its purpose is to trigger distributive conditional type behavior over each union member. - This is one of the most concise patterns in type-level TypeScript.
