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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With