Documentation
deepFlatten

deepFlatten

Recursivly flattens the array until there are no elements satisfying Array.isArray() (opens in a new tab), while maintaining proper typesaftey.

Calling Array.prototype.flat (opens in a new tab) with an argument of Number.POSITIVE_INFINITY or some other arbitrarily large number produces awkward types.

Note that generally speaking, Array.prototype.flat (opens in a new tab) should be preferred. deepFlatten should only be opted for when the depth is variable or unknown.

import { arr } from "@tsly/arr";
 
const things = [[0], [[1]]];
//    ^? (number[] | number[][])[]
 
const flattened = arr(things).deepFlatten().take();
//    ^? number[]
 
console.log(flattened);
// [0, 1]

Edit on CodeSandbox (opens in a new tab)

import { arr } from "@tsly/arr";
 
const gizmos = [[["str"]], [false], [[5]]];
//    ^? (string[][] | boolean[] | number[][])[];
 
const flattened = arr(things).deepFlatten().take();
//    ^? (string | boolean | number)[]
 
console.log(flattened);
// ["str", false, 5]

Edit on CodeSandbox (opens in a new tab)

Using Array.prototype.flat

const nums = [[0], [[1]]].flat(Number.POSITIVE_INFINITY);
// ^? FlatArray<number[] | number[][], 0 | 1 | 2 | -1 | 3 | 4 | 5 | ...