Course contentsShow
← TypeScript
Lesson 1383 of 1,79632. Advanced PatternsFree lesson

Flattening Nested Tuples

Recursively flattening nested tuple types into a single-level tuple.

Flattening Nested Tuples

What you'll learn: How to recursively transform nested tuple types like [1, [2, [3, 4]]] into a single-level tuple [1, 2, 3, 4] at the type level.

What Are Nested Tuples?

Just like arrays can contain other arrays, tuple types can contain other tuple types. For example:

type Nested = [1, [2, 3], [[4]]];

This creates a structure where some elements are themselves tuples. While this is valid TypeScript, you might need a flat version: [1, 2, 3, 4].

The Core Pattern: Recursive Conditional Types

Flattening nested tuples requires recursion — a type that references itself while breaking down the structure piece by piece.

The strategy:

  1. Check if the tuple is empty — if so, return an empty tuple
  2. Extract the first element using index access
  3. If that element is itself a tuple, flatten it recursively
  4. Concatenate the flattened first element with the flattened rest
type Flatten<T extends readonly unknown[]> = 
  T extends readonly [infer First, ...infer Rest]
    ? First extends readonly unknown[]
      ? [...Flatten<First>, ...Flatten<Rest>]
      : [First, ...Flatten<Rest>]
    : [];

How It Works

Let's trace through Flatten<[1, [2, 3], 4]>:

  • Extract First = 1, Rest = [[2, 3], 4]
  • 1 is not a tuple → result includes [1, ...Flatten<[[2, 3], 4]>]
  • Next iteration: First = [2, 3], Rest = [4]
  • [2, 3] is a tuple → flatten it: [...Flatten<[2, 3]>, ...Flatten<[4]>]
  • This resolves to [2, 3, 4]
  • Final result: [1, 2, 3, 4]
type Result = Flatten<[1, [2, 3], [[4, 5]]]>;
// Result = [1, 2, 3, 4, 5]

Key Takeaway: Flattening nested tuples uses recursive conditional types with infer to detect tuple elements, flatten them individually, and spread them back into a single-level tuple — a powerful pattern for transforming complex type structures.