react-redux-typescript-guide: Incorrect action creator type when using bindActionCreators and redux-thunk

Specifically I have this action defined.

getTransitionForm: (params: GetTransitionFormParams) =>
    (dispatch: Dispatch<RootState>, getState: () => RootState, extraArgument: any) => 
         Promise<any>;

When mapped as follows as per your guide from section “Connected Container without OwnProps using Type Inference” https://github.com/piotrwitek/react-redux-typescript-guide#connected-container-with-ownprops

export const mapDispatchToProps = (dispatch: Dispatch<RootState>) =>
  bindActionCreators(
    {
      getTransitionForm,
    },
    dispatch
  );
const dispatchProps = returntypeof(mapDispatchToProps);

The resulting value of dispatchProps is

const dispatchProps: {
    getTransitionForm: (params: GetTransitionFormParams) =>
        (dispatch: Dispatch<RootState>, getState: () => RootState, extraArgument: any) => 
             Promise<any>;
}

I believe after binding it should be.

const dispatchProps: {
    getTransitionForm: (params: GetTransitionFormParams) => Promise<any>;
}

Which I expect is not going to be easy to derive. I only discovered this as I wanted to do something with the returned promise. Thanks for your great guide.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

If people are still looking at how to get the correct typings for bindActionCreators when passing in ThunkActions, I’ve got an open PR to fix this, specifically the line: https://github.com/reduxjs/redux-thunk/pull/224/files#diff-b52768974e6bc0faccb7d4b75b162c99R31

Overloading the function definition and conditionally returning a different object type if the action passed is of type ThunkAction:

declare module 'redux' {
  /**
   * Overload for bindActionCreators redux function, returns expects responses
   * from thunk actions
   */
  function bindActionCreators<M extends ActionCreatorsMapObject<any>>(
    actionCreators: M,
    dispatch: Dispatch,
  ): { [N in keyof M]: ReturnType<M[N]> extends ThunkAction<any, any, any, any> ? (...args: Parameters<M[N]>) => ReturnType<ReturnType<M[N]>> : M[N] }
}

Let me know if it fits your needs

@rluiten this time I have thoroughly investigated and I found you are right, types are not correct but only for the thunk action creators. Specifically bindActionCreators could have been augmented by redux-thunk to fix that behaviour.

The types returned from connect should have bound action creators, but it seems they are still typed as thunk action creators so dispatch is not correctly applied.

When I changed mapDispatchToProps declaration to not use bindActionCreators it’s fixed, you can try: const mapDispatchToProps = (dispatch: Dispatch) => ({ updateRegion: (payload: RegionModel) => dispatch(SitesReducer.updateRegion(payload)), });

The second one works because this time dispatch is correctly augmented by redux-thunk typings.

The necessary fix is to augment bindActionCreators to apply augmented dispatch that can handle thunk actions, but it’s not possible with current Type Inference limitations.

Sorry for the delay responding. It’s been a while since I looked at this, but I’ll get the conversation started with what I have and see if that’s helpful. I’m not totally sure if my code will directly translate, but hopefully, it will be helpful.

type OwnProps = {
  foo: string,
};

type ReduxStateProps = {
  bar: boolean,
};

type DispatchProps = {
  myAC: typeof myAC.bound,
  // note the type of myAC is: (x: ArgType) => AbortableAction<FluxAction<void>>
  // see below for relevant type definitions of return type
};

type ComponentProps = OwnProps & ReduxStateProps & DispatchProps;

class ComponentFoo extends React.Component<ComponentProps> { // ... }

function mapStateToProps(state: RootState, props: OwnProps): ReduxStateProps {
  // ...
  return {
    bar: true
  };
}

function mapDispatchToProps(dispatch: Dispatch<RootState>) {
  const acs = {
    myAC,
  };
  return bindActionCreators<typeof acs, DispatchProps>(acs, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(DecisionDetails);

For reference, ReturnType<typeof mapDispatchToProps> is:

{
    myAC: (x: ArgType) => AbortableAction<FluxAction<void>>;
}

The utility types involved are:

export interface AbortableAction<R> extends BluebirdPromise<R> {
  abort: () => void;
  url: string;
}

export interface FluxAction<Payload> extends Action {
  type: string;
  payload: Payload;
  meta?: any;
  error: boolean;
}

export type ActionCreator<Arg, Payload> = {
  (a: Arg): FluxAction<Payload>,
  type: string,
  bound: (x: Arg) => AbortableAction<FluxAction<Payload>>,
  arg: Arg,
  pl: Payload,
};

Hopefully, that helps. Let me know if there are any questions, and I’ll try to answer them.

I freely admit I might have flubbed something. But it compiles with no errors and appears to work (but that might be pure fluke).

Definition of my Component and its properties.

interface RouteParams {
  transitionStatementId: number;
}
export interface OwnProps extends RouteComponentProps<RouteParams> {}
export const mapDispatchToProps = (dispatch: Dispatch<RootState>) =>
  bindActionCreators(
    {
      getTransitionForm
    },
    dispatch
  );
const stateProps = returntypeof(mapStateToProps);
const dispatchProps = returntypeof(mapDispatchToProps);
export type Props = typeof stateProps & typeof dispatchProps & OwnProps;

class TransitionForm extends React.Component<AllProps, OwnState> { /* etc */ }

Inside my components member functions the type of 'props.getTransitionForm` appears to be. (conveniently visible in VSCode but I did not assume VSCode was correct) I am calling the action from a submit() function that is part of redux-form.

(params: GetTransitionFormParams) =>
        (dispatch: Dispatch<RootState>, getState: () => RootState, extraArgument: any) => 
             Promise<any>;

The fire*Action() functions are just examples.

I setup a test and i can use await it compiles with no errors, and appears to work correctly.

    const getPayload = {state, apiUrls, transitionStatementId: 23};
    const getResult  = getTransitionForm(getPayload);
    try {
        await getResult;
        fireGotAction();
    } catch (e) { 
        fireErrorGotAction();
    }

If I use .then() I get a compile error.

The getResult above gives me the compile error where i try to use .then(). TS2339: Property 'then' does not exist on type 'ThunkAction<Promise<any>, RootState, any>'.

    const getPayload = {state, apiUrls, transitionStatementId: 23};
    const getResult  = getTransitionForm(getPayload);
    getResult.then(() => fireGotAction(), () => fireErrorGotAction());  

This leads me to believe the types are not really correct, I am not implying they are easy to fix or can be fixed, I fudged the type for myself for now. It appears await isn’t enforcing type constraints equivalently to .then(), and since the underlying value is actually a promise await works anyway.

Currently i am just casting the property action to any to call then and all seems well with the world.

Thanks for your response, I raised this more to see if it rings a bell with you that might point out something I had missed or possibly even something you can address. I think its complex enough some sort of fix might not be easy and may require much deeper type knowledge than I have, or even typescript may not be able to do express the constraint in its current version.

Thanks,