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.
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).
type PermutationsOfTuple<T extends unknown[], Prev extends unknown[] = []> =
T extends [infer First, ...infer Rest]
? [First, ...PermutationsOfTuple<[...Prev, ...Rest]>] | PermutationsOfTuple<Rest, [...Prev, First]>
: Prev extends []
? []
: neverHow it works:
T from left to right. Prev accumulates elements that have been skipped over (not yet placed).T has at least one element, we branch into two possibilities via a union (|):
First now: We put First at the head of the result and recursively permute the remaining elements [...Prev, ...Rest] (everything we skipped plus everything after First).First for later: We move First into Prev and continue looking at Rest for the next element to place.T is empty, we check Prev: if Prev is also empty, we have placed all elements and return []. If Prev still has elements but T is empty, we return never since this path cannot complete a valid permutation on its own (those elements will be handled by the "place now" branch).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.
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