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

TypeScript定义items为Item类型数组时报2322元素数量不匹配错误如何解决?

问题原因

你定义Example类型的items字段时,误用了TypeScript元组语法。[Item]代表的是长度固定为1、仅包含1个Item类型元素的元组,和你想要的「任意长度的Item类型数组」语义不符,因此给items赋值长度为2的数组时会触发类型不匹配报错:

Type '[{ id: number; size: number; }, { id: number; size: number; }]' is not assignable to type '[Item]'. Source has 2 element(s) but target allows only 1.(2322)

解决方法

定义任意长度的Item类型数组有两种标准写法:

  • 简写语法:Item[]
  • 泛型语法:Array<Item>

修改后的完整代码如下:

type Item = {
    id: number;
    size: number;
}
type Example = {
    name: string;
    // 替换为数组写法即可
    items: Item[]
}

var obj: Example = {
    name: "test",
    items: [
        {
            id: 1,
            size: 10
        },
        {
            id: 2,
            size: 34
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:09:04