Recursively flatten array up to depth times. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement FlattenDepth<T, Depth> which recursively flattens a nested array up to a specified number of times, with the depth defaulting to 1.
Recursively flatten array up to depth times.
For example:
type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2> // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1If the depth is provided, it's guaranteed to be positive integer.
Change the following code to make the test cases pass (no type check errors).
We need to flatten one level at a time and decrement a depth counter on each pass. A helper type flattens exactly one level, and we repeatedly apply it until the depth is exhausted or the array is already flat.
type FlattenOnce<T extends any[]> = T extends [infer First, ...infer Rest]
? First extends any[]
? [...First, ...FlattenOnce<Rest>]
: [First, ...FlattenOnce<Rest>]
: []
type FlattenDepth<
T extends any[],
Depth extends number = 1,
Count extends any[] = []
> = Count['length'] extends Depth
? T
: FlattenOnce<T> extends T
? T
: FlattenDepth<FlattenOnce<T>, Depth, [...Count, 1]>How it works:
FlattenOnce<T> performs a single level of flattening by spreading any array elements one level deepCount is a tuple that acts as a counter, incrementing by one element each recursive stepCount['length'] equals Depth, we have flattened enough times and return T as-isFlattenOnce<T> extends T is an early exit: if flattening produces the same type, the array is already fully flat, so we stop early (this prevents infinite recursion for very large depth values)This challenge helps you understand depth-controlled recursive type flattening and how to apply this concept 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