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.
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).
/* _____________ 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']
|Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Permutation<T, U = T> =
[T] extends [never]
? []
: U extends U
? [U, ...Permutation<Exclude<T, U>>]
: neverHow it works:
[T] extends [never] check is the base case. We wrap T in a tuple to prevent distributive behavior -- a bare T extends never would itself distribute and produce never instead of matching. When the union is exhausted (i.e., T is never), we return an empty tuple [].U = T creates a copy of the original union. The U extends U pattern triggers distributive conditional types, which iterates over each member of the union one at a time.U, we place it at the front of a tuple and recursively compute Permutation<Exclude<T, U>> -- the permutations of the remaining members with U removed.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.