使用打字稿在Redux thunk中返回Promise

时间:2018-08-17 15:48:23

标签: typescript redux-thunk

我收到此打字稿错误:Property 'then' does not exist on type 'ThunkAction<Promise<boolean>, IinitialState, undefined, any>'.

请帮助!

我如何配置商店并包括以下类型:

    return createStore(
      rootReducer,
      intialState,
      require('redux-devtools-extension').composeWithDevTools(
        applyMiddleware(
          thunk as ThunkMiddleware<IinitialState, any>,
          require('redux-immutable-state-invariant').default()
        )
      )

动作创建者:

type ThunkResult<R> = ThunkAction<R, IinitialState, undefined, any>;

export function anotherThunkAction(): ThunkResult<Promise<boolean>> {
  return (dispatch, getState) => {
    return Promise.resolve(true);
  }
}

然后在我的组件中有一个prop接口:

interface IProps {
  anotherThunkAction: typeof anotherThunkAction;
}

然后:

  componentWillMount() {
    this.props.anotherThunkAction().then(() => {console.log('hello world')})
  }

在我也使用react-i18next的地方连接:

export default translate('manageInventory')(
  connect(
    mapStateToProps,
    {
      anotherThunkAction
    }
  )(ManageInventory)
);

1 个答案:

答案 0 :(得分:3)

我认为您的调度工作不正确...您在调用操作而不将其传递给商店。

如果直接调用该操作,则会返回:

ThunkAction<Promise<boolean>, IinitialState, undefined, any>

正如tsc告诉您的那样,它没有then函数。当您通过dispatch运行某些程序时,它将ThunkResult<R>变成R

您还没有向商店展示如何connect使用组件-但我认为这就是问题所在。这是一个示例:

type MyThunkDispatch = ThunkDispatch<IinitialState, undefined, any>

const mapDispatchToProps = (dispatch: MyThunkDispatch) => ({
  anotherThunkAction: () => dispatch(anotherThunkAction())
})

connect(null, mapDispatchToProps)(MyComponent)

这会将anotherThunkAction添加到props中,您可以调用它,它会正确调用您的操作并返回承诺。