0Pricing
TypeScript Academy · Lesson

Flatten and UnwrapPromise Utilities

Write types that unwrap nested generic structures.

The Flatten Problem

JavaScript arrays can be nested. A Flatten utility type recursively removes array wrappers from a type, returning the innermost element type.

type Flatten<T> = T extends (infer U)[] ? Flatten<U> : T;
type A = Flatten<number[][][]>; // number
type B = Flatten<string[]>;     // string

Non-Recursive Flatten (One Level)

A single-level flatten mirrors Array.prototype.flat(1) — it unwraps exactly one level of nesting.

type FlatOnce<T> = T extends (infer U)[] ? U : T;
type A = FlatOnce<number[][]>; // number[]
type B = FlatOnce<string[]>;   // string

All lessons in this course

  1. DeepPartial and DeepReadonly
  2. Flatten and UnwrapPromise Utilities
  3. TupleToUnion and UnionToIntersection
  4. Publishing a Type Utility Library
← Back to TypeScript Academy