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 can I declare an array of unknown elements where the first one must be a string?

I’m trying to write a function that accepts an array of arrays. The inner array can have any number of elements of any type, but the first one must be a string.

The following is a valid input array:

[
    ['2022-03-04T00:00:00Z', 64, 10],
    ['2022-03-05T00:00:00Z', 61, 12],
    ['2022-03-06T00:00:00Z', 66, 14],
]

But the following is not a valid input:

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

[
    [0, '2022-03-04T00:00:00Z', 64, 10],
    [1, '2022-03-05T00:00:00Z', 61, 12],
    [2, '2022-03-06T00:00:00Z', 66, 14],
]

I tried the following:

function formatDateLabels( array: [[string, ...any[]]] ){
    ...
}

but the compiler complains:

Argument of type '[[string, number, number], [string, number, number], [string, number, number]]' is not assignable to parameter of type '[[string, ...any[]]]'.
  Source has 3 element(s) but target allows only 1.(2345)

How can I declare the types correctly?

>Solution :

The example’s [[string, ...any[]]] parameter type is expecting a tuple that contains a single nested tuple with the first value being a string and allowing any other entry types after it.

This type should be changed to [string, ...any[]][] which expects an array of tuples that accept the first value as a string and any entry types after it.

function formatDateLabels(array: [string, ...any[]][]){
    // code
}

formatDateLabels([
    ['2022-03-04T00:00:00Z', 64, 10],
    ['2022-03-05T00:00:00Z', 61, 12],
    ['2022-03-06T00:00:00Z', 66, 14],
]);

Playground link.

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