'How to add type on store and combine reducers in react-redux with TypeScript
I have this type error that breaks the app using react-redux with TypeScript.
Error:
This comes from root_store.ts file which creates my store:
const persistConfig = {
key: 'root',
storage
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const configureStore = () => {
const middlewares = [thunk];
const middlewareEnhancer = applyMiddleware(...middlewares);
const enhancers = [middlewareEnhancer];
const composedEnhancers = composeWithDevTools(...enhancers);
const store = createStore(persistedReducer, composedEnhancers);
const peristor = persistStore(store);
return { store, peristor };
};
export const { store, peristor } = configureStore();
and on my root reducer. I have this code.
export const rootReducer = combineReducers({
user
});
export type RootState = ReturnType<typeof rootReducer>;
If I remove the type from combineReducers fn like combineReducer<AppState> I will have that error which I don't know why.
Here's the code for the user reducer:
const user = (state = userInitialState, action: UserActionTypes): IUser => {
switch (action.type) {
case UserEnumTypes.USER_INFO: {
return {
...state,
...action.payload
};
}
case UserEnumTypes.USER_LOGOUT: {
return {
...state,
...action.payload
};
}
default: {
return state;
}
}
};
export default user;
Here's the code for the user actions:
export const setupUserOnSuccessLoginORSignup = (user: IUser): ISetupUserOnSuccessLoginORSignup => ({
type: UserEnumTypes.USER_INFO,
payload: {
...user
}
});
export const logoutUser = (): ILogoutUser => ({
type: UserEnumTypes.USER_LOGOUT,
payload: {
...userInitialState
}
});
Here's the action types for the users:
export enum UserEnumTypes {
USER_INFO = 'USER_INFO',
USER_LOGOUT = 'USER_LOGOUT'
}
export interface ISetupUserOnSuccessLoginORSignup {
type: typeof UserEnumTypes.USER_INFO;
payload: {
id: number | null;
username: string;
email: string;
createdAt?: string;
updatedAt?: string;
usersGameGroups?: IUsersGameGroup[];
posts?: IPost[];
};
}
export interface ILogoutUser {
type: typeof UserEnumTypes.USER_LOGOUT;
payload: {
id: number | null;
username: string;
email: string;
};
}
export type UserActionTypes = ISetupUserOnSuccessLoginORSignup | ILogoutUser;
I followed this from redux guide https://redux.js.org/recipes/usage-with-typescript#type-checking-reducers
and read this opposite problem. Typescript: How to type combined reducers?
Weird though because he didn't export the combineReducers but maybe he had it in single file.
I wanted to add any type in const store:any = createStore(persistedReducer, composedEnhancers); this will fix the error but is it advisable, my concern is I will lose the type checking when I map props to my component?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

