I have an array like this:
const rows: Row[] = [
[
1,
["breakfast", "apples"],
],
[
2,
["lunch", "burguer"],
["dinner", "pasta"],
],
];
The array can have any number of items, each one is an array itself with the first item always being a number and the rest being arrays of 2 strings.
This is the type I came up with:
type Row = [number, ...[string, string]];
But it's not working, it says that the 2nd item should be a string instead of an array of strings:
Type '[string, string]' is not assignable to type 'string'.
Here's a playground with an example.
CodePudding user response:
A rest element in a tuple type should be of the form [...YourDesiredElementType[]]
. You want elements to be [string, string]
, so the rest element looks like ...[string, string][]
:
type Row = [number, ...[string, string][]];
And then things work as desired:
const rows: Row[] = [
[
1,
["bananas", "apples"],
["steak", "burguer"],
],
[
2,
["orange", "lemon"],
["pizza", "pasta"],
],
]; // okay