#296Medium

Permutation

Implement permutation type that transforms union types into the array that includes permutations of unions. Learn union type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a Permutation type that transforms a union type into a union of all possible tuple orderings of its members.

Challenge Instructions: Permutation

Medium

Implement permutation type that transforms union types into the array that includes permutations of unions.

[object Object]

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

ChallengeSolution
/* _____________ Your Code Here _____________ */

type Permutation<T> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

type cases = [
  Expect<Equal<Permutation<'A'>, ['A']>>,
  Expect<
    Equal<
      Permutation<'A' | 'B' | 'C'>,
      | ['A', 'B', 'C']
      | ['A', 'C', 'B']
      | ['B', 'A', 'C']
      | ['B', 'C', 'A']
      | ['C', 'A', 'B']
      | ['C', 'B', 'A']
    >
  >,
  Expect<
    Equal<
      Permutation<'B' | 'A' | 'C'>,
      | ['A', 'B', 'C']
      | ['A', 'C', 'B']
      | ['B', 'A', 'C']
      | ['B', 'C', 'A']
      |

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Permutation<T, U = T> =
  [T] extends [never]
    ? []
    : U extends U
      ? [U, ...Permutation<Exclude<T, U>>]
      : never

How it works:

This challenge helps you understand distributive conditional types and recursive union manipulation, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts