Array flat Depth Recursion In Types
flat(1) only unwraps one array level and the compiler tracks it: flat(2) and flat(Infinity) return deeper element unions, so type errors surface wrong depths.
Code
const nested: Array<number | Array<number | Array<number>>> = [
1,
[2, 3],
[4, [5]],
];
const flat1 = nested.flat(1);
const flat2 = nested.flat(2);
const flatAll = nested.flat(Infinity);
// 类型跟着深度走:flat(1) 还保留一层嵌套,flat(2) 与 Infinity 才是纯 number
type One = typeof flat1;
type Two = typeof flat2;
const pure: number[] = flat2;
console.log(JSON.stringify(flat1), JSON.stringify(flat2), JSON.stringify(flatAll));
console.log(flat1.length, flat2.length, flatAll.length, pure.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
[1,2,3,4,[5]] [1,2,3,4,5] [1,2,3,4,5]
5 5 5 5The route to the output
The file’s state is a handful of top-level bindings: flat1, flat2, flatAll.
Caveats
- Complete in itself — no import reaches beyond what the runtime already ships.
Key statements
const flatAll = nested.flat(Infinity);
const flat1 = nested.flat(1);
const flat2 = nested.flat(2);
Interactive Tools for This Topic
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `flat1`, `flat2`, `flatAll`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.