1

Please see this minimum code below.

function zip<T>(...arrs: T[][]): T[][] {
  return arrs
}

zip([1,2,3], ['a', 'b', 'c'])
// Type 'string' is not assignable to type 'number'.ts(2322)

zip<number | string>([1,2,3], ['a', 'b', 'c'])
// Ok, but a little bit bother to me.

I created a function using generics and rest properties.

When I directly use zip([1,2,3], ['a', 'b', 'c']), I expect that typescript automatically finds out I'm using number | string type, is there any way to achieve this?

enter image description here

2
  • 1
    That's doing the right thing now. You've defined a function that zips arrays of the same type, your arrays are of different types, so you get an error. You should have to add information (like the explicit union type) if that's actually the behaviour you want. Commented Mar 19, 2019 at 8:23
  • I think I got it right now, thank you! Commented Mar 19, 2019 at 8:27

1 Answer 1

1

Typescript sees the first parameter is number[] and this fixes T and then you get an error for the second. While in theory T could be inferred to string | number I would argue the current behavior is usually a good thing, it is more likely infering unions would lead to unexpected errors in other places.

You can get the compiler to accept the call you want if you make the compiler consider all the arguments as a whole, not individually, using tuples in rest parameters:

function zip<T extends any[][]>(...arrs: T): (T[number][number])[][] {
    return arrs
}

zip([1,2,3], ['a', 'b', 'c'])

T will be a tuple type for the sample call ([number[], string[]], so to get the item type we use T[number][number] (which will be string | number for the sample call), and the get back to the array of arrays using [][]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.