Yuzhe's Blog

yuzhes

Flatten Depth

Flatten Depth

Problem Link

Problem

Recursively flatten array up to depth times.

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 1

If the depth is provided, it’s guaranteed to be a positive integer.

Solution

Approach: Recursive Flattening with Depth Counter

We flatten one level at a time, decrementing the depth counter using a tuple accumulator.

type FlattenOnce<T extends unknown[]> = T extends [infer Head, ...infer Tail]
  ? Head extends unknown[]
    ? [...Head, ...FlattenOnce<Tail>]
    : [Head, ...FlattenOnce<Tail>]
  : []

type FlattenDepth<
  T extends unknown[],
  Depth extends number = 1,
  Count extends unknown[] = []
> = Count['length'] extends Depth
  ? T
  : FlattenDepth<FlattenOnce<T>, Depth, [...Count, unknown]>

How it works:

  1. FlattenOnce<T> flattens the array by exactly one level.
  2. Count is a tuple accumulator — its length tracks how many times we’ve flattened.
  3. When Count['length'] === Depth, we stop and return T.

Key Takeaways