TypeScript报错:'never[]'类型参数无法赋值给'never'类型
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
Actionstype was undefined, so TypeScript couldn't infer what actions the reducer expected. - Your reducer returned
void(fromconsole.log()) instead of a validStatevalue. This made TypeScript incorrectly infer the reducer's state type asnever, which clashed with your initial state[](inferred asnever[]).
With these fixes, TypeScript will correctly understand your state and action types, and that annoying error should vanish!
内容的提问来源于stack exchange,提问作者user4383363

