flow icon indicating copy to clipboard operation
flow copied to clipboard

Array.prototype.flat returns mixed on nested arrays

Open FezVrasta opened this issue 1 year ago • 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

  • Link to Try-Flow or Github repo: https://flow.org/try#0MYewdgzgLgBGCuBbARgUwE4QFxyW9A2gLowC8MBlAjEbQHQBmANgIZQAUATAJQDcQA

FezVrasta avatar Jan 30 '23 12:01 FezVrasta

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

darichey avatar Jan 30 '23 16:01 darichey

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

FezVrasta avatar Jan 30 '23 17:01 FezVrasta