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 cases = [
Expect<
Equal<
CartesianProduct<1 | 2, 'a' | 'b'>,
[2, 'a'] | [1, 'a'] | [2, 'b'] | [1, 'b']
>
>,
Expect<
Equal<
CartesianProduct<1 | 2 | 3, 'a' | 'b' | 'c'>,
| [2, 'a']
| [1, 'a']
| [3, 'a']
| [2, 'b']
| [1, 'b']
| [3, 'b']
| [2, 'c']
| [1, 'c']
| [3, 'c']
>
>,
Expect<Equal<CartesianProduct<1 | 2, 'a' | never>, [2, 'a'] | [1, 'a']>>,
Expect<
Equal<
CartesianProduct<'a', Function | string>,
['a', Function] | ['a', string]
>
>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.