How would you write a conditional type that recursively flattens a nested array type of arbitrary depth?
Short answer
Use a conditional type combined with infer and recursion: if T matches an array of arrays, recurse into the inner array type; otherwise, return T as the base case — the compiler will keep re-evaluating the type alias against itself until it bottoms out.
Advertisement
AModel answer
Use a conditional type combined with infer and recursion: if T matches an array of arrays, recurse into the inner array type; otherwise, return T as the base case — the compiler will keep re-evaluating the type alias against itself until it bottoms out.
type DeepFlatten<T> = T extends (infer U)[] ? DeepFlatten<U> : T;
type A = DeepFlatten<number[][][]>; // numberReal-world example
Deriving the final, fully unwrapped element type from a deeply nested array structure without manually specifying the depth.
Likely follow-ups
- Does TypeScript place any limit on how deep recursive conditional types can go?
Related topics