TypeScript只读数组联合调用includes/indexOf报never参数错误如何解决
问题原因
你遇到的报错本质是TypeScript对数组联合类型的方法参数做了交集运算:areas[area].adjacencies 的类型是 readonly [2,3,4,5] | readonly [6,7,8],两个数组的元素没有交集,所以includes方法的入参类型被推导为两个数组元素类型的交集never,自然无法传入数字3。
解决方案
方案1:直接类型断言(最简单)
你已经定义好了元素联合类型ElementUnion,只需要在调用includes前把数组断言为readonly ElementUnion[]即可:
(areas[area].adjacencies as readonly ElementUnion[]).includes(3);
同理indexOf也可以用相同的方式处理:
(areas[area].adjacencies as readonly ElementUnion[]).indexOf(3);
方案2:类型收窄(最安全)
如果areas的key数量不多,可以通过收窄area的类型来规避联合数组的问题:
if (area === 'area1') { areas[area].adjacencies.includes(3); // 此时adjacencies类型确定为readonly [2,3,4,5] } else { areas[area].adjacencies.includes(3); // 此时adjacencies类型确定为readonly [6,7,8] }
方案3:封装通用工具函数(最通用)
可以封装一个类型安全的includes工具函数,不需要每次手动写断言,还支持后续类型收窄:
function includes<T extends U, U>(arr: readonly T[], searchElement: U): searchElement is T { return arr.includes(searchElement as T); } // 直接调用即可,无类型报错 includes(areas[area].adjacencies, 3);
内容的提问来源于stack exchange,提问作者crazyones110
相关产品推荐
相关产品推荐

