Infer Type of asyncThunk action

Viewed 351

I needed to use useAppDispatch to be able to await on dispatching async thunk actions

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

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

Iam dispatching action as

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

The problem is, there are strict typescript checks, Iam getting this

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.

how can a give the type of Function ?

1 Answers

Please follow the TS app setup approach shown in the Redux and RTK docs, and particularly the process for inferring the type of AppDispatch from store.dispatch and creating a useAppDispatch hook:

// 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

The AppDispatch type will then understand that thunks can be dispatched, and the thunk return value will be returned from dispatch, allowing you to do dispatch(someThunk()).then().

Related