redux-thunk:通过store.dispatch()调用操作时缺少属性“类型”

Shi*_*hin 10 typescript reactjs redux redux-thunk react-redux

我在网上发现了类似的问题,但是redux-thunk通过调用Action 时没有解决方案store.dispatch()

我有以下内容action

export class DBActions {
  static startDatabase(): ThunkAction<Promise<void>, {}, IClientState, AnyAction> {
    return async (dispatch: ThunkDispatch<{}, {}, AnyAction>, getState: () => IClientState): Promise<void> => {
      return new Promise<void>((resolve) => {
        dispatch(DBActions.connectDatabase())
        setTimeout(() => {
          let connection: (Connection | undefined) = getDBConnection(getState())
          if (connection) {
            dispatch(DBActions.getImports(connection))
            resolve()
          }
        }, 2000)
      })
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

通过添加到mapDispatchToProps组件中时,此方法可以正常工作,但store.ts在定义a之后直接在my内部调用时,则不会出现问题storestore.dispatch(DBActions.startDatabase())导致:

TS2345: Argument of type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type 'ThunkAction<Promise<void>, {}, {}, AnyAction>'.
Run Code Online (Sandbox Code Playgroud)

任何帮助和建议,不胜感激!

sli*_*wp2 10

您可以使用TypeScript 的声明合并Dispatch来扩展接口。使用重载签名扩展接口。然后方法可以调度异步操作。reduxDispatchThunkDispatchstore.dispatch()

store.ts

import { applyMiddleware, createStore } from 'redux';
import thunk, { ThunkAction } from 'redux-thunk';
import { DBActions } from './action';

declare module 'redux' {
  interface Dispatch<A extends Action = AnyAction> {
    <S, E, R>(asyncAction: ThunkAction<R, S, E, A>): R;
  }
}

const store = createStore((state) => state, applyMiddleware(thunk));

// dispatch async action
store.dispatch(DBActions.startDatabase()).then(() => {
  console.log(store.getState());
});

// dispatch sync action
store.dispatch(DBActions.connectDatabase());
Run Code Online (Sandbox Code Playgroud)

软件包版本:

"redux": "^4.1.0",
"redux-thunk": "^2.3.0"
"typescript": "^4.2.4"
Run Code Online (Sandbox Code Playgroud)


Ram*_*ino 7

避免错误消息的简单解决方法 - 尽管它不是解决方案:

dispatch<any>(DBActions.getImports(connection))
Run Code Online (Sandbox Code Playgroud)

  • 这可能是一种解决方法,但它让我摆脱了困境。谢谢你! (2认同)
  • 为什么要使用“any”的打字稿? (2认同)