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.
type perm = Permutation<'A' | 'B' | 'C'>; // ['A', 'B', 'C'] | ['A', 'C', 'B'] | ['B', 'A', 'C'] | ['B', 'C', 'A'] | ['C', 'A', 'B'] | ['C', 'B', 'A']Change the following code to make the test cases pass (no type check errors).
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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount