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
相关产品推荐
相关产品推荐

