Define react redux state with typescript

Viewed 58

I have todoReducer.ts file like this

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;

Then the root reducer like this

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>;

In my todoList.jsx file

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

    }

This gives me an error

Property 'items' does not exist on type 'never'.

Seems initialState's items object not recognizing by the ts.

How do I fix this issue?

Updated After the comment, I have added the

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

But I hover over the store.getState it says the same error. I think still it doesn't pick the type enter image description here

2 Answers

You should declare type when createStore

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

You should update typw for initialState when create reducer

const initialState: Array<Item > = {
  items: [],
};
Related