#3243Medium

FlattenDepth

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.

Challenge Instructions: FlattenDepth

Medium

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 1

If 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).

Loading...

Detailed Explanation

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:

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.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount