Given an array of unique elements, return all possible subsequences. Learn union type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Subsequence type that returns a union of all possible subsequences of a given tuple, preserving the original element order.
Given an array of unique elements, return all possible subsequences.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
For example:
[object Object]Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<Subsequence<[1, 2]>, [] | [1] | [2] | [1, 2]>>,
Expect<
Equal<
Subsequence<[1, 2, 3]>,
[] | [1] | [2] | [1, 2] | [3] | [1, 3] | [2, 3] | [1, 2, 3]
>
>,
Expect<
Equal<
Subsequence<[1, 2, 3, 4, 5]>,
| []
| [1]
| [2]
| [3]
| [4]
| [5]
| [1, 2]
| [1, 3]
| [1, 4]
| [1, 5]
| [2, 3]
| [2, 4]
| [2, 5]
| [3, 4]
| [3, 5]
| [4, 5]
| [1, 2, 3]
| [1, 2, 4]
| [1, 2, 5]
| [1, 3, 4]
| [1, 3, 5]
| [1, 4, 5]
| Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Subsequence<T extends any[]> = T extends [infer F, ...infer Rest]
? [F, ...Subsequence<Rest>] | Subsequence<Rest>
: []How it works:
F and the remaining elements Rest.F in the subsequence ([F, ...Subsequence<Rest>]) or exclude it (Subsequence<Rest>).[] (the empty tuple) when no elements remain, representing the empty subsequence.[1, 2], the expansion produces [1, 2] | [1] | [2] | [].This challenge helps you understand recursive type-level combinatorics and union type generation and how to apply these concepts in real-world scenarios.
This challenge is originally from here.