How to handle the return type of dispatch with Redux Promise Middleware?

1k Views Asked by At

Redux Promise Middleware seems to handle the promise resolution of an action payload. For example, consider this action creator that uses a Promise as payload:

export default class ActionCreators {
  public static fetchAllUsers(): FetchAction {
    return {
      type: actionTypes.FETCH_ALL_USERS,
      payload: fetch("api.com/users")
    };
  }
}

When using this action creator, TypeScript expects an Action returned data, instead of the Promise that is actually returned because of redux-promise-middleware.

So the following code will not compile because Property 'then' does not exist on type 'Action'.

dispatch(ActionCreators.fetchAllUsers())
    .then(response => {
        // do something with response
    })

Typescript expects returned properties like payload and type, which are actually not returned because the promise has been handled already and has ACTUALLY been returned.

.then is ready to be used, but typescript will not compile because it expects something else.

I guess the question is: How to write the correct typings to handle redux-promise-middleware actions, while providing redux' connect-function with the correct dispatch types for mapDispatchToProps etc.

1

There are 1 best solutions below

0
On

You can use conditional types. E.g.

export interface BaseAction<TPayload> {
   type: string;
   payload: TPayload;
}

export interface Dispatch {
    <T extends BaseAction<any>>(action: T): 
         T extends BaseAction<Promise<infer R>> ? Promise<R>:  T

}