Holis
Holis

Reputation: 215

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?

Upvotes: 3

Views: 1078

Answers (1)

phry
phry

Reputation: 44106

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

Upvotes: 1

Related Questions