Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type N array of strings with TypeScript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading