• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Type of zip and unzip array functions?

Resolved: Type of zip and unzip array functions?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have zip and unzip functions like this:
I have no idea how to type the return types though. Is it even possible?
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 for unzip that does what you want.
Let’s see if it works:
Playground
Here is an alternative solution that is fully compatible with the solution above. But for array literals, this will produce more accurate return types.
Playground

If you have better answer, please add a comment about this, thank you!

arrays typescript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Vue 3 watchEffect dependency tracking after asynchronous code

22/03/2023

Resolved: Watching state object in pinia doesn’t fire when object changes

22/03/2023

Resolved: Create From/To Pairs by sequential date R dplyr

22/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.