Home > Enterprise >  Adding types to async func inside createAsyncThunk
Adding types to async func inside createAsyncThunk

Time:05-01

I've got an issue by trying to add types for arguments while creating async function in createAsyncThunk:

export const setLangAsync = createAsyncThunk<
  { lang: string },
  { fileName: string },
  { getState: RootState; dispatch: AppDispatch }
>(
  'i18n/setLangAsync',
  async (lang: string, fileName: string, { getState, dispatch }) => {
 ...
}

here is the error:

(parameter) getState: any
Argument of type '(lang: string, fileName: string, { getState, dispatch }: 
{ getState: any; dispatch: any; }) => Promise<unknown>' 
is not assignable to parameter of type 'AsyncThunkPayloadCreator<
{ lang: string; }, { fileName: string; }, { getState: { i18n: I18nInterface; }; 
dispatch: ThunkDispatch<...> & Dispatch<...>; }>'.ts(2345)
Binding element 'getState' implicitly has an 'any' type.ts(7031

I seem to be totally lost here. I hope someone could help me to understand what I'm doing wrong. Thank you in advance!

CodePudding user response:

createAsyncThunk's payload creator function takes two arguments, not three.

As for the generic arguments:

  • the first is the return type
  • the second is the argument type
  • the third are various options
export const setLangAsync = createAsyncThunk<
  WhatEverTheFunctionReturnTypeIs,
  { lang: string, fileName: string },
  { getState: RootState; dispatch: AppDispatch }
>(
  'i18n/setLangAsync',
  async ({ lang, fileName }, { getState, dispatch }) => {
 ...
}
  • Related