flatten
takes an array of any data type and produces an array with every nested array flatten.
For example, [{}, 'hello', 2, [3, ['ay'], 'oi oi']
becomes [{}, 'hello', 2, 3, 'ay', 'oi oi']
, and [[[[5]]]]
becomes [5]
.
I need an interface that would describe such a function. I started writing it thinking it would be simple, but then I stuck with describing an array of anything but other arrays.
interface Flatten {
(any[]): ...?
}
Any ideas are welcome, thank you :))
If you know all the data types flat array should return, you may define it like below:
In your example you had nested empty object, so I assume you want it to contain only flat arrays too,
FlatObj
is definition of it.Now if you try to assign nested arrays in any
FlatArr
variable, it should complain about it.Link to playground
If you are looking for a Type Guard, here one example for
FlatArr
andFlatObj
:To make FlatArr, you can define a function for it. I made two functions below. One makes Arrays flat, the other makes sure object arrays are flat too: