Skip to content

TS conflict between AppThunk and createAsyncThunk.withTypes #4602

Open
@zshuzh

Description

What docs page needs to be fixed?

In the Redux Docs > Usage With Typescript > Type Checking Redux Thunks, it recommends using the following to type thunks:

export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType, // return type of the thunk function
  RootState, // state type used by getState
  unknown, // any "extra argument" injected into the thunk
  UnknownAction // known types of actions that can be dispatched
>

In the RTK Docs > Usage with Typescript > Defining a Pre-Typed createAsyncThunk, it recommends the following to type createAsyncThunk:

const createAppAsyncThunk = createAsyncThunk.withTypes<{
  state: RootState
  dispatch: AppDispatch
  rejectValue: string
  extra: { s: string; n: number }
}>()

I'm using both of these in my apps, but when I try to dispatch a thunk created using createAppAsyncThunk from a regular thunk, it's flagging a type error.

What is the problem?

From what I can see, it seems the two approaches type dispatch differently. The first approach (with AppThunk) types the dispatch parameter as ThunkDispatch<RootState, unknown, UnknownAction> but the second approach (with createAsyncThunk.withTypes) types the dispatch parameter as ThunkDispatch<RootState, undefined, UnknownAction> which is causing a problem,

What should be changed to fix the problem?

I was able to fix the problem like this:

export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  undefined, // changed this from unknown to undefined
  UnknownAction
>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions