Flatten Depth
Less than 1 minuteTC-Medium
Flatten Depth
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 1If 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:
FlattenOnce<T>flattens the array by exactly one level.Countis a tuple accumulator — its length tracks how many times we've flattened.- When
Count['length'] === Depth, we stop and returnT.
Key Takeaways
- Tuple length as a counter is the canonical way to do bounded recursion in TypeScript types.
- Separating "one step" (
FlattenOnce) from "repeat N times" keeps the logic clean.
