The Flatten Pattern for Nested Types
What you'll learn: How to recursively unwrap nested array or promise structures using conditional types that check and recurse on their own structure.
The Core Challenge
Sometimes you receive types that are deeply nested — arrays containing arrays containing arrays, or promises wrapping promises wrapping promises. The "Flatten" pattern uses conditional types with infer to recursively unwrap these layers until you reach the innermost type.
How It Works
Think of it like peeling an onion: you check if the outer layer is an array (or promise), extract what's inside, then call the same type on that inner value to check if it needs peeling too. This self-reference continues until you hit something that isn't wrapped anymore.
Here's the pattern for flattening arrays:
type Flatten<T> = T extends Array<infer U>
? Flatten<U> // Recursively flatten the inner type
: T; // Base case: no more arrays
type Test1 = Flatten<number[][][]>; // number
type Test2 = Flatten<string[]>; // string
type Test3 = Flatten<boolean>; // boolean (already flat)
The conditional checks: "Is T an array?" If yes, extract the element type U and recursively call Flatten<U>. If no, you've reached the bottom — return T as-is.
Flattening Promises
The same pattern works for unwrapping nested promises:
type Awaited<T> = T extends Promise<infer U>
? Awaited<U> // Recursively unwrap the promise
: T; // Base case: not a promise
type Test4 = Awaited<Promise<Promise<number>>>; // number
type Test5 = Awaited<Promise<string>>; // string
You can even combine patterns to handle mixed nesting, checking for both arrays and promises in sequence.
Why It Matters
This pattern is essential for working with unknown nesting depths — like API responses, flattened data structures, or deeply chained async operations — where you need type safety all the way down.
Key Takeaway: The Flatten pattern uses conditional types with infer and recursion to unwrap nested structures layer by layer until reaching the core type, enabling type-safe operations on arbitrarily nested data.