Home > Mobile >  How can I declare an array of unknown elements where the first one must be a string?
How can I declare an array of unknown elements where the first one must be a string?

Time:05-16

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:

[
    [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?

CodePudding user response:

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.

CodePudding user response:

You could create your own interface of specific types for the inner array.

The values for the above could be for example a string and then another array of type any, so that you can hold an infinite amount of items.

https://www.typescriptlang.org/docs/handbook/interfaces.html

  • Related