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

如何在TypeScript中正确配置useReducer?解决类型报错与状态初始化问题

问题解决方案

1. 解决useReducer类型报错

报错的核心原因是useReducer的泛型参数使用错误:useReducer接受的第一个泛型参数不是状态类型,是Reducer函数的类型定义。

修复步骤:

  • 首先在BasketReducer.ts中导出IBasketAction接口,方便外部引用
  • 补全BasketReducer的逻辑:reducer必须覆盖所有action类型的处理,且要有默认分支返回当前state,避免返回undefined,同时显式声明返回值类型为IBasketState
    // BasketReducer.ts 修正后代码
    import type { IBasketState } from "../contexts/BasketContext";
    
    export interface IBasketAction {
        type: "Add item" | "Remove item";
        payload?: string;
    }
    
    const BasketReducer = (basketState: IBasketState, action: IBasketAction): IBasketState => {
        switch (action.type) {
            case "Add item":
                console.log("Add iteeeeeeem");
                return { ...basketState };
            case "Remove item":
                // 后续补充商品移除逻辑即可
                return { ...basketState };
            default:
                return basketState;
        }
    };
    
    export default BasketReducer;
    
  • 修正useReducer的写法,两种方案二选一:
    1. 直接省略泛型,让TS自动推导类型,最简单:
      const [basketState, dispatch] = useReducer(BasketReducer, initialState);
      
    2. 显式声明泛型,需要先导入React的Reducer类型:
      // BasketContext.tsx 顶部导入
      import type { Reducer, ReactNode } from "react";
      // 导入IBasketAction
      import BasketReducer, { IBasketAction } from "../reducers/BasketReducer";
      // useReducer 写法
      const [basketState, dispatch] = useReducer<Reducer<IBasketState, IBasketAction>>(BasketReducer, initialState);
      

额外提示:你代码中使用了ReactNode但未导入,需要在BasketContext.tsx顶部补充导入import type { ReactNode } from "react"。

2. products初始化为空数组的实现

你当前无法把products设为空数组,是因为IBasketState中products的类型定义错误:你写的[{name: string; price: number; quantity: number}]是长度固定为1的元组类型,要求数组必须有且仅有1个元素,所以不能赋值为空数组。

修复步骤:

把IBasketState里的products类型改成普通数组类型即可:

export interface IBasketState {
    products: {
        name: string;
        price: number;
        quantity: number;
    }[];
    totalPrice: number;
}

修改后initialState就可以直接写成空数组:

const initialState: IBasketState = {
    products: [],
    totalPrice: 0,
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 10:27:03