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

使用useState遇类型不兼容错误:回调函数无法赋值给参数类型

问题:useState结合TypeScript时的类型不匹配错误

我在使用useState时遇到如下TypeScript错误:
Argument of type '(previousState: IsProducts) => { list: IsProduct[]; }' is not assignable to parameter of type 'IsProducts'

不清楚类型定义哪里存在问题,希望能得到技术方向上的指点。相关代码如下:

export interface IsProduct {
    name: string;
    price: number;
    quantity: number;
}

export interface IsProducts {
    list: IsProduct[];
}

const [products, setProducts] = useState<IsProducts | undefined>({
        list: [
            {
                name: 'Test One',
                price: 20,
                quantity: 2,
            },
            {
                name: 'Test Two',
                price: 10,
                quantity: 1,
            },
        ],
    });

setProducts((previousState: IsProducts) => {
                return {
                    ...previousState,
                    list: previousState.list.map((product: IsProduct, idx: number) => {
                        if (idx === index) {
                            return {
                                ...product,
                                quantity: product.quantity >= 10 ? (product.quantity = 10) : product.quantity + 1,
                            };
                        }
                        return product;
                    }),
                };
            });

另外,将setProducts从IsProductContext中移除后,上述错误会消失,但会触发上下文相关的其他错误,上下文定义如下:

export interface IsProductContext {
    products: IsProducts;
    setProducts: (products: IsProducts) => void;
}

解决方案

核心问题:上下文的setProducts类型定义不完整

React的useState返回的setter函数(即setProducts)支持两种调用方式:

  • 直接传入新的状态值(IsProducts类型)
  • 传入一个回调函数,接收旧状态并返回新状态((prevState: IsProducts) => IsProducts类型)

但你定义的IsProductContext里,setProducts只允许传IsProducts类型的参数,完全限制了回调函数的使用方式,这就是报错的根本原因。

具体修复步骤

  1. 修正上下文的类型定义
    先从React导入必要的类型:
import { Dispatch, SetStateAction } from 'react';

然后修改IsProductContext接口:

export interface IsProductContext {
    products: IsProducts;
    setProducts: Dispatch<SetStateAction<IsProducts>>;
}

Dispatch<SetStateAction<T>>是React提供的标准类型,专门用来描述useState的setter函数,自动兼容值和回调两种调用方式。

  1. 优化useState的初始类型
    你给useState加了| undefined,但实际上已经传入了合法的初始值,TS可以自动推导类型,或者明确写成:
const [products, setProducts] = useState<IsProducts>({
    // 初始值不变
});

这样后续使用previousState时就不用额外处理undefined的情况。

  1. 清理冗余的赋值操作
    在quantity的三元表达式里,product.quantity = 10是直接修改原对象的冗余操作,改成直接返回数值即可:
quantity: product.quantity >= 10 ? 10 : product.quantity + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:45:30