You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript为特定结构的嵌套数组定义类型?

问题描述

我有如下数组:

const rows: Row[] = [
  [
    1,
    ["breakfast", "apples"],
  ],
  [
    2,
    ["lunch", "burguer"],
    ["dinner", "pasta"],
  ],
];

该数组可包含任意数量的元素,每个元素本身是一个数组,其第一个元素始终为数字,其余元素均为包含两个字符串的数组。

我尝试定义如下类型:

type Row = [number, ...[string, string]];

但该类型无法正常工作,出现报错:

Type '[string, string]' is not assignable to type 'string'.

解决方案

你定义的Row类型错误在于,...[string, string]会把这个二元字符串数组展开为单个string类型的剩余元素要求,这和你实际需要的“剩余元素是[string, string]数组”不匹配。

正确的类型定义应该将剩余元素指定为[string, string]的数组类型,使用...[string, string][]:

type Row = [number, ...[string, string][]];

这个类型表示:第一个元素必须是数字,后面可以跟任意数量(包括0个)的[string, string]类型数组,完全匹配你的数据结构。

内容的提问来源于stack exchange,提问作者Camilo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:36:27