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[]>; // stringNon-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[]>; // stringAll lessons in this course
- DeepPartial and DeepReadonly
- Flatten and UnwrapPromise Utilities
- TupleToUnion and UnionToIntersection
- Publishing a Type Utility Library