#21220Medium

Permutations of Tuple

Given a generic tuple type `T extends unknown[]`, write a type which produces all permutations of `T` as a union. Learn union type manipulation, tuple manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll write a type that takes a tuple and produces a union of all possible permutations of that tuple's elements, preserving their individual types.

Challenge Instructions: Permutations of Tuple

Medium

Given a generic tuple type T extends unknown[], write a type which produces all permutations of T as a union.

For example:

PermutationsOfTuple<[1, number, unknown]>
// Should return:
// | [1, number, unknown]
// | [1, unknown, number]
// | [number, 1, unknown]
// | [unknown, 1, number]
// | [number, unknown, 1]
// | [unknown, number ,1]

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<PermutationsOfTuple<[]>, []>>,
  Expect<Equal<PermutationsOfTuple<[any]>, [any]>>,
  Expect<
    Equal<PermutationsOfTuple<[any, unknown]>, [any, unknown] | [unknown, any]>
  >,
  Expect<
    Equal<
      PermutationsOfTuple<[any, unknown, never]>,
      | [any, unknown, never]
      | [unknown, any, never]
      | [unknown, never, any]
      | [any, never, unknown]
      | [never, any, unknown]
      | [never, unknown, any]
    >
  >,
  Expect<
    Equal<
      PermutationsOfTuple<[1, number, unknown]>,
      | [1, number, unknown]
      | [1, unknown, number]
  

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type PermutationsOfTuple<T extends unknown[], Prev extends unknown[] = []> =
  T extends [infer First, ...infer Rest]
    ? [First, ...PermutationsOfTuple<[...Prev, ...Rest]>] | PermutationsOfTuple<Rest, [...Prev, First]>
    : Prev extends []
      ? []
      : never

How it works:

This challenge helps you understand recursive tuple manipulation combined with union distribution, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts