如何解决 useReducer hook 的类型错误 "argument is not assignable to parameter of type never"?

How do I solve the type error "argument is not assignable to parameter of type never" for useReducer hook?

将鼠标悬停在我的 useReducer 函数中的 todos 变量上: const [state, dispatch] = useReducer(reducer, todos); 给出以下类型错误。

Argument of type 'TodoState[]' is not assignable to parameter of type 'never'.

我尝试在我的 reducer 函数中添加 TodoState[] 作为 return 类型,以确保我不会意外地 returning never[] 但是,错误仍然存在:

相关代码如下:

interface TodoState {
  id: string;
}

interface TodoAction {
  type?: 'CREATED' | 'DELETED' | 'UPDATED';
  payload?: TodoState;
}

interface TodoReducer {
  state: TodoState[];
  action: TodoAction;
}

interface TodosProviderProps {
  children: ReactChildren;
  todos: TodoState[];
}

const reducer = ({ state = [], action = {} }: TodoReducer): TodoState[] => {
  const { payload, type } = action;

  const mutatedItem = payload;
  if (!mutatedItem) {
    return state;
  }
  const mutatedIndex = state.findIndex((item) => item.id === mutatedItem.id);
  switch (type) {
    case 'CREATED':
      if (mutatedIndex < 0) {
        state.push(mutatedItem);
      }
      break;
    case 'DELETED':
      if (mutatedIndex >= 0) {
        state.splice(mutatedIndex, 1);
      }
      break;
    case 'UPDATED':
      state[mutatedIndex] = mutatedItem;
      break;
    default:
      return state;
  }

  return state;
};

export function TodosProvider({ children, todos }: TodosProviderProps) {
  const [state, dispatch] = useReducer(reducer, todos);// type error for todos here

  // rest of code
}

看完文档后,我发现,reducer 函数传递了两个参数,而不是你解构的对象。

所以,该行应该是:

const reducer = (state:TodoState[] = [], action:TodoAction = {}): TodoState[] => {