推断 asyncThunk 操作的类型

时间:2021-03-21 13:59:36

标签: reactjs typescript redux react-redux redux-thunk

我需要使用 useAppDispatch 来等待调度异步 thunk 操作

interface AppDispatch<A extends Action = AnyAction> {
  <T extends A | Function>(action: T): T extends Function ? Promise<AnyAction> : T;
}

function useAppDispatch(): AppDispatch {
  return useDispatch();
}

Iam 调度动作为

appDispatch(fetchSocialPagePermissions()).then((pagesResponse) => {
      const facebookConnectedPages = pagesResponse?.payload?.facebookPageResponse?.pages;
      if (facebookConnectedPages && facebookConnectedPages.length > 0) {
        dispatch(exportCollateral({fulfillmentType: FulfillmentType.SHARE_INSTAGRAM}));
      }
    });

问题是,有严格的打字稿检查, 我得到这个

Don't use `Function` as a type. The `Function` type accepts any function-like value.
It provides no type safety when calling the function, which can be a common source of bugs.

如何给出函数的类型?

1 个答案:

答案 0 :(得分:2)

请遵循 the TS app setup approach shown in the Redux and RTK docs,特别是从 AppDispatch 推断 store.dispatch 的类型并创建 useAppDispatch 钩子的过程:

// app/store.ts
import { configureStore } from '@reduxjs/toolkit'
// ...

const store = configureStore({
  reducer: {
    one: oneSlice.reducer,
    two: twoSlice.reducer
  }
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
// app/hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

AppDispatch 类型然后会理解可以调​​度 thunk,并且将从 dispatch 返回 thunk 返回值,允许您执行 dispatch(someThunk()).then()