Search code examples
typescriptreduxredux-thunk

Type for a redux action creator


I am currently confused by the type of my action creator in a react-redux app that I am working on. I have this action creator with types on both side of the equation and TS compiler said everything is perfect:

const setItem: ActionCreator<ThunkResult<void>> = (...): ThunkResult<void> => (...): void => {
  dispatch({
    ...
  });
};

where ThunkResult is ThunkResult<R> = ThunkAction<R, IStoreState, null, ActionTypes>

What is not clear for me why on the left side the returned type of the function is ActionCreator<ThunkResult<void>> however, on the right side it's ThunkResult<void>.

Note: I skipped args since they are not important in this question.

I am not sure whether it's misunderstanding of TS functions or it's an issue in TS.


Solution

  • I can make it easier to understand for you First, just think ActionCreator is a Type and it will be

    type ActionCreator<T> = (params) : T => T
    // then you can defined the variable
    const setItem: ActionCreator<string> = (params) : string => ""
    

    Like ThunkResult

    type ThunkResult<T> = (params): T => T
    // then you can defined the variable
    const thunk: ThunkResult<number> = (params): number => 0
    

    So, if you mix them will be like this

    ActionCreator<ThunkResult<void>> = (params) : ThunkResult<void> => ThunkResult<void>
    // and 
    ThunkResult<void> = (params):void => void
    // so
    ActionCreator<ThunkResult<int>> = (params): ThunkResult<void> => (params2): void => void // just replace ThunkResult<void> above with (params):void => void
    

    Hope it helps