首页 > 解决方案 > 用 typescript 定义 react redux 状态

问题描述

我有这样的 todoReducer.ts 文件

import ActionType from "../types";

const initialState = {
  items: [],
};

interface Item {
  task: string;
  priority: string;
  id: string;
  isActive: boolean;
  label: string;
}

function reducer(state = initialState, action: any) {
  switch (action.type) {
    case ActionType.ADD_ITEM:
      return { ...state, items: [action.payload, ...state.items] };

    case ActionType.CROSS_ITEM:
      return {
        ...state,
        items: state.items.map((e: Item) => {
          if (e.id === action.payload) e.isActive = false;
          return e;
        }),
      };

    default:
      return state;
  }
}
export default reducer;

然后像这样的root reducer

import { combineReducers } from "redux";
import authReducer from "./authReducer";
import todoReducer from "./todoReducer";

const reducers = combineReducers({
  auth: authReducer,
  todo: todoReducer,
});

export default reducers;

export type State = ReturnType<typeof reducers>;

在我的 todoList.jsx 文件中

    import {State} from "../store/reducers/index"
    const TodoList = ()=>{
     const items = useSelector((state:State) => state.todo.items);
...

    }

这给了我一个错误

“从不”类型上不存在属性“项目”。

似乎 initialState 的items对象没有被 ts 识别。

我该如何解决这个问题?

更新 评论后,我添加了

export type State = ReturnType<typeof store.getState>;

但是我将鼠标悬停在 store.getState 上,它说同样的错误。我认为它仍然没有选择类型 在此处输入图像描述

标签: reactjstypescriptvue.jsreact-redux

解决方案


你应该在什么时候声明类型createStore

const store = createStore(reducers, ...)
export type State = ReturnType<typeof store.getState>;

推荐阅读