Ga naar inhoud

TypeScript Reference · Utility Types

Flatten and Unwrap helper types

Build your own TypeScript Flatten, Unwrap and ElementOf helper types with conditional types and infer, and learn when they beat the built-in Awaited.

TypeScript ships a fixed set of utility types, but the same tools they are made from (conditional types, infer and recursion) are available to you. A Flatten helper removes one layer of array from a type, an Unwrap helper peels a wrapper such as a promise or a box, and a DeepFlatten keeps going until nothing is left to remove.

These helpers are a good first exercise in type-level programming: each one is a single conditional type that asks "does this type have the shape I want to open?" and, if so, captures the inner type with infer.

TypeScript
type Flatten<T> = T extends readonly (infer U)[] ? U : T;

type A = Flatten<string[]>; // string
type B = Flatten<number>;   // number (not an array, returned unchanged)

Try it

TypeScript One level of array

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Unwrapping promises, boxes and nested arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

The general recipe for an unwrapping helper:

TypeScript
type Helper<T> = T extends Wrapper<infer Inner> ? Inner : T;
Part Description
T extends Wrapper<infer Inner> Tests whether T has the wrapper shape and, if so, captures the contents as Inner.
? Inner The true branch: the unwrapped type. For a recursive helper, call the helper again on Inner.
: T The false branch: usually the type unchanged, so non-wrapped types pass through safely.

Result: a type, computed when T is known. There is no runtime value.

Edge cases: Flatten<never> is never, because a naked type parameter distributes over an empty union.

Usage notes

  • Distribution. When T is a naked type parameter, a union is processed member by member. Flatten<string[] | number> is string | number. Wrap in a tuple, [T] extends [...], to stop distribution.
  • Why readonly (infer U)[]. A readonly array is not assignable to a mutable one. Matching readonly U[] accepts both mutable and readonly arrays.
  • Tuples. Flatten<[string, number]> gives string | number, because a tuple is an array of its union of element types.
  • Recursion has limits. A recursive helper handles reasonably deep nesting, but very deep or infinitely recursive types hit the instantiation depth limit and report an error.
  • Do not rebuild what exists. For promises use the built-in Awaited<T>, which also understands thenables. Hand-rolled helpers are for shapes the standard library does not cover, such as your own Box.
  • Keep the fallback branch. Returning T (not never) in the false branch makes the helper safe to apply to anything.
  • Types only. These helpers do not change values. Pair them with a function that does the runtime work, as flattenAll above, and assert the return type yourself.