Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple type vs. array-of-union-type

I'm probably missing something silly here. I thought the tuple type [string, number] was roughly equivalent to the array-of-union type (string | number)[], and that the following was therefore legal:

function lengths (xs: string[]): [string, number][] {
   return xs.map((x: string) => [x, x.length])
}

However tsc 1.4 complains:

Config.ts(127,11): error TS2322: Type '(string | number)[][]' is not assignable to type '[string, number][]'.
  Type '(string | number)[]' is not assignable to type '[string, number]'.
    Property '0' is missing in type '(string | number)[]'.

What am I doing wrong?

like image 212
Roly Avatar asked Mar 01 '15 13:03

Roly


1 Answers

This answer courtesy Daniel Rosenwasser. You can get the behavior you want by giving your lambda a return type.

function lengths(xs: string[]): [string, number][] {
    return xs.map((x): [string, number] => [x, x.length]);
}

More information here.

like image 99
Roly Avatar answered Oct 03 '22 07:10

Roly