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

ChallengeSolution
type cases = [
  Expect<Equal<FlattenDepth<[]>, []>>,
  Expect<Equal<FlattenDepth<[1, 2, 3, 4]>, [1, 2, 3, 4]>>,
  Expect<Equal<FlattenDepth<[1, [2]]>, [1, 2]>>,
  Expect<Equal<FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>, [1, 2, 3, 4, [5]]>>,
  Expect<Equal<FlattenDepth<[1, 2, [3, 4], [[[5]]]]>, [1, 2, 3, 4, [[5]]]>>,
  Expect<Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 3>, [1, 2, 3, 4, [5]]>>,
  Expect<
    Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 19260817>, [1, 2, 3, 4, 5]>
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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