2

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.

1 Answer 1

2

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

Playground link to code

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.