A recursive flatten that drills through arrays of any depth. The signature accepts (T | T[])[] and returns T[] — so the type system reflects the collapse.
export function flatten<T>(arr: (T | T[])[]): T[] {
return arr.reduce<T[]>(
(acc, item) =>
acc.concat(Array.isArray(item) ? flatten(item as (T | T[])[]) : item),
[],
);
}
Compared to Array.prototype.flat
arr.flat(Infinity)does the same thing without the recursion, but with a wider type signature (unknown[]).- This version keeps element typing precise when you know the leaf type up front.