Question:
I have zip and unzip functions like this:I think it would be nice if
zip([1, 2, 3], ["a", "b"])
returned with a type of [number | undefined, string | undefined][]
. It seems that there is an answer here as someone in the comments pointed out that does precisely this. Likewise, it would be nice if unzip([1, "a"], [2, "b"], [3, undefined])
returned a type of [number[], string[]]
or maybe [number[], (string | undefined)[]]
depending on whichever is easiest.I am a typescript noob, so naturally I tried to find some types on the internet, but they all seem to go the “lazy” route and type returns as
any
.If this is even possible, how would I type the return types of these two functions (as well as similar functions where you “invert” the type of an array)?
Answer:
I got a solution forunzip
that does what you want.Here is an alternative solution that is fully compatible with the solution above. But for array literals, this will produce more accurate return types.
If you have better answer, please add a comment about this, thank you!