typescripttypesafe-actions

Create a root reducer with typesafe-actions


I'm using typesafe-actions and would like to create a root reducer that will allow me to handle global actions like LOGGED_OUT, in order to clear state. Like in the answer to this question.

I've tried a few things but I keep losing the type safety that typesafe-actions provides, and the reducer reverts to an any type.

I have a pretty vanilla type safe actions setup. I haven't posted the permutation solutions of implicit typing that I've tried, because I don't think it will add any clarity to the question.

The closest to a solution being found I could find was in this thread. The maintainer of type safe actions himself posted a response and mentioned that he already had a solution, though from that point on there were no links or references provided.

Any help would be great.

For the record, I can get this to functionally work following the pattern as per the Stack overflow question I posted, however the types are broken.


Solution

  • Turns out I already solved this 9 months ago on a separate project and forgot.

    import { combineReducers } from 'redux';
    import auth from '../modules/auth/reducer';
    import feed from '../modules/feed/reducer';
    import post from '../modules/post/reducer';
    import profile from '../modules/profile/reducer';
    import { StateType, Reducer, RootAction } from 'typesafe-actions';
    import { signOut } from 'modules/auth/actions';
    
    const appReducer = combineReducers({
      auth,
      feed,
      post,
      profile
    });
    
    type RootState = StateType<typeof appReducer>;
    
    const clearOnSignOutReducer: Reducer<RootState, RootAction> = (
      state,
      action
    ) => {
      if (action.type === signOut().type) {
        state = undefined;
      }
      return appReducer(state, action);
    };
    
    export default clearOnSignOutReducer;