facebook/flow

Array.prototype.flat returns mixed on nested arrays

FezVrasta opened this issue · 2 comments

Flow version: 0.198.2

Expected behavior

The resulting array should be all numbers.

Actual behavior

The problem seems to be the type definition itself, why is it like that?
https://github.com/facebook/flow/blob/main/lib/core.js#L832

Giving a general type to flat requires some type machinery not (yet) available in Flow. The simple case is somewhat easy, and depending on your use case, you might be able to work around the issue by defining some overloaded function like:

declare function flatten<T>(arr: $ReadOnlyArray<$ReadOnlyArray<T>>, depth: 2): Array<T>;
declare function flatten<T>(arr: $ReadOnlyArray<$ReadOnlyArray<$ReadOnlyArray<T>>>, depth: 3): Array<T>;

But this won't work for the case of different levels of nesting and stopping at a certain depth (e.g., [[1], [[2]], [[[3]]]].flat(2)).

Some previous discussion:
#6602
#7397

Could support for a couple levels be added to the lib though? It should cover most of the use cases