Type Tuple vs. array-of-union-type

I probably miss something stupid here. I thought that the type of the [string, number] tuple was roughly equivalent to the type of the join type (string | number)[] , and therefore the following was 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?

+6
source share
1 answer

This answer has been kindly provided by Daniel Rosenwasser. You can get the behavior you need by providing your lambda return type.

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

More details here .

+5
source

Source: https://habr.com/ru/post/983182/


All Articles