Given 2 sets (unions), return its Cartesian product in a set of tuples, e.g. Learn union type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement CartesianProduct<T, U> which takes two union types and returns a union of all possible tuple pairs combining one member from each set.
Given 2 sets (unions), return its Cartesian product in a set of tuples, e.g.
CartesianProduct<1 | 2, 'a' | 'b'>
// [1, 'a'] | [2, 'a'] | [1, 'b'] | [2, 'b']Change the following code to make the test cases pass (no type check errors).
type CartesianProduct<T, U> = T extends T
? U extends U
? [T, U]
: never
: neverHow it works:
T extends T is a distributive conditional type pattern that iterates over each member of the union T. Even though the condition is always true, wrapping it in a conditional causes TypeScript to distribute over the unionU extends U similarly distributes over each member of the union UT and a single member from U, the type produces a tuple [T, U][T, U] pairs, which is exactly the Cartesian productCartesianProduct<1 | 2, 'a' | 'b'> produces [1, 'a'] | [1, 'b'] | [2, 'a'] | [2, 'b']This challenge helps you understand distributive conditional types and how to leverage them for generating combinatorial union types in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount