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

TypeScript报错:'never[]'类型参数无法赋值给'never'类型

Fixing the "never[] is not assignable to never" Error in React useReducer with TypeScript

Hey there! Let's sort out this TypeScript error you're hitting with useReducer. The issue comes down to two key problems: missing type definitions for your actions, and an incorrect return value in your reducer. Here's how to fix it step by step:

1. Define the Actions Type Explicitly

Right now TypeScript has no clue what your Actions type looks like—this is a major source of the confusion. Let's define it so TypeScript knows exactly what actions your reducer can handle:

// Adjust payload types to match your actual use case
type Actions = 
  | { type: "add"; payload: Todo } // Action to add a new todo
  | { type: "remove"; payload: number }; // Action to remove by index (example)

2. Fix the Reducer's Return Value

Your current reducer returns the result of console.log(), which is void (nothing). But a reducer must always return the updated state (of type State, which is Todo[]). Let's rewrite the reducer logic correctly:

const TodoReducer = (state: State, action: Actions): State => {
  switch (action.type) {
    case "add":
      // Return a new array with the new todo appended
      return [...state, action.payload];
    case "remove":
      // Return a new array excluding the target todo
      return state.filter((_, index) => index !== action.payload);
    default:
      // Always return the current state for unrecognized actions
      return state;
  }
};

3. Optional: Explicitly Type useReducer (For Extra Clarity)

While TypeScript can now infer the types correctly on its own, you can explicitly specify the generics for useReducer to make your code even more readable:

const [todos, dispatch] = React.useReducer<React.Reducer<State, Actions>>(TodoReducer, []);

Why You Got the Error

The original code had two critical issues that confused TypeScript:

  • The Actions type was undefined, so TypeScript couldn't infer what actions the reducer expected.
  • Your reducer returned void (from console.log()) instead of a valid State value. This made TypeScript incorrectly infer the reducer's state type as never, which clashed with your initial state [] (inferred as never[]).

With these fixes, TypeScript will correctly understand your state and action types, and that annoying error should vanish!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:52:26