facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.09k stars 1.86k forks source link

Array.prototype.flat returns mixed on nested arrays #8999

Open FezVrasta opened 1 year ago

FezVrasta commented 1 year ago

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

darichey commented 1 year ago

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

FezVrasta commented 1 year ago

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