Search code examples
typescriptreduxredux-thunk

Redux Thunk TS return type definition


I'm trying to define the returned type of my Redux Thunk function.

Basically I'm dispatching an action that will eventually return a string.

So I wrote:

export type AppThunk = ThunkAction<Promise<string>, IState, unknown, Action>;

export const getServiceUrl = (url: string): AppThunk => {
  return async (dispatch) => {
    dispatch(startLoading(retrievingData));
    try {
      const { serviceUrl } = await getJson(url);
      return serviceUrl;
    } catch (error) {
      dispatch(stopLoading());
    }
  };
};

Inside my component I have:

const serviceUrl = await dispatch(
  getServiceUrl(
    `/api/microservice/email`
  )
);

if (serviceUrl) {
  window.location.assign(redirectUrl);
}

I'm constantly getting TS2345: Argument of type ‘AppThunk’ is not assignable to parameter of type ‘string | URL.

But I don't understand why.

How can I declare the return type of my thunk function?


Solution

  • Your dispatch is probably not typed correctly - please make sure to set up a typed useDispatch hook, as stated in the TypeScript Quick Start:

    import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
    import type { 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