我正在尝试编写一个接受数组数组的函数。内部数组可以有任意数量的任何类型的元素,但第一个必须是字符串。
以下是有效的输入数组:
[
['2022-03-04T00:00:00Z', 64, 10],
['2022-03-05T00:00:00Z', 61, 12],
['2022-03-06T00:00:00Z', 66, 14],
]
但以下内容不是有效的输入:
[
[0, '2022-03-04T00:00:00Z', 64, 10],
[1, '2022-03-05T00:00:00Z', 61, 12],
[2, '2022-03-06T00:00:00Z', 66, 14],
]
我尝试了以下方法:
function formatDateLabels( array: [[string, ...any[]]] ){
...
}
但编译器抱怨:
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)
如何正确声明类型?
该示例的[[string, ...any[]]]
参数类型需要一个包含单个嵌套元组的元组,其中第一个值是字符串,并允许在其后的任何其他条目类型。
此类型应更改为[string, ...any[]][]
,它需要一个元组数组,这些元组接受第一个值作为字符串以及它之后的任何条目类型。
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],
]);
游乐场链接。
您可以为内部数组创建自己的特定类型的接口。
例如,上面的值可以是字符串,然后是 any 类型的另一个数组,以便您可以保存无限数量的项目。
https://www.typescriptlang.org/docs/handbook/interfaces.html