#27862Medium

CartesianProduct

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.

Challenge Instructions: CartesianProduct

Medium

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).

ChallengeSolution
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]
    >
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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

How it works:

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.

Share this challenge

Learn the Concepts