TypeScript中点击事件调用setCardItem触发void类型不匹配报错
问题描述
在React+TypeScript项目中调用useState生成的状态更新方法setCardItem时,抛出如下TypeScript错误:
Argument of type '(prev: cartItemType[]) => cartItemType[] | void[]' is not assignable to parameter of type 'SetStateAction<cartItemType[]>'.
(翻译:传入的参数类型为(prev: cartItemType[]) => cartItemType[] | void[],不符合参数要求的SetStateAction<cartItemType[]>类型,本质是状态更新回调的返回值包含void类型数组,无法匹配要求的cartItemType[]类型)
报错根因
错误出在已加购商品的数量更新逻辑里:你写的prev.map()回调函数用大括号包裹了代码块,但没有显式写return返回值,导致map遍历每个元素时默认返回undefined,最终得到void[]类型的数组,和状态要求的cartItemType[]类型不匹配。
修复方案
给map的回调函数加上显式return,或者去掉大括号用箭头函数的隐式返回写法即可,修正后的完整代码如下:
type cartItemType = { id: number; title: string; price: number; description: string; category: string; image: string; amount: number; }; const [cardItem, setCardItem] = useState<cartItemType[]>([]); const handleClickAddToCard = (clickedItem: cartItemType) => { setCardItem(prev => { // 判断商品是否已经在购物车中 const isItemInCard = prev.find((item) => item.id === clickedItem.id); if (isItemInCard) { // 修复点:map回调显式返回处理后的商品对象 return prev.map((item) => { return item.id === clickedItem.id ? { ...item, amount: item.amount + 1 } : item; }); // 也可以写成更简洁的隐式返回形式,效果一致: // return prev.map(item => // item.id === clickedItem.id ? { ...item, amount: item.amount + 1 } : item // ); } // 商品首次加入购物车的逻辑 return [...prev, { ...clickedItem, amount: 1 }]; }); };
补充说明
箭头函数的返回规则需要注意:
- 如果箭头函数后直接跟表达式、不写大括号,会自动返回表达式的执行结果,属于隐式返回
- 如果箭头函数后用大括号包裹了多行代码块,必须手动书写
return关键字才会返回指定值,否则默认返回undefined,也就是TS识别到的void类型
内容的提问来源于stack exchange,提问作者hossein ranjbar
相关产品推荐
相关产品推荐

