[英]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.数组可以有任意数量的项目,每个项目本身都是一个数组,第一项总是一个数字,rest 是 arrays 的 2 个字符串。
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'.
类型 '[string, string]' 不可分配给类型 'string'。
Here's a playground with an example .这是一个带有示例的游乐场。
A rest element in a tuple type should be of the form [...YourDesiredElementType[]]
. 元组类型中的 rest 元素应采用
[...YourDesiredElementType[]]
形式。 You want elements to be [string, string]
, so the rest element looks like ...[string, string][]
:您希望元素为
[string, string]
,因此 rest 元素看起来像...[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.