You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Improve doc clarity around TypeScript and createAsyncThunk usage
I had a difficult time figuring out how to get proper TypeScript responses for dispatched thunk actions. I read the docs several times, and even though the answer was there (use type narrowing via match), I missed it each time.
I think I skipped it because the relevant information was nested under the "Manually defining thunkAPI types" category, which I wasn't doing in my case.
Since this type narrowing is very useful and relevant even when you're not manually typing `thunkAPI`, I'm making a proposal in this PR to move this information slightly higher in the doc and give it a dedicated section.
For more context, see my question [on Discord](https://discord.com/channels/102860784329052160/103538784460615680/1264479048524890224).
I hope you'll consider making this small change. Thank you!
You can leverage checks against `action.payload` and `match` as provided by `createAction` as a type-guard for when you want to access known properties on defined types. Example:
The second argument to the `payloadCreator`, known as `thunkApi`, is an object containing references to the `dispatch`, `getState`, and `extra` arguments from the thunk middleware as well as a utility function called `rejectWithValue`. If you want to use these from within the `payloadCreator`, you will need to define some generic arguments, as the types for these arguments cannot be inferred. Also, as TS cannot mix explicit and inferred generic parameters, from this point on you'll have to define the `Returned` and `ThunkArg` generic parameter as well.
While this notation for `state`, `dispatch`, `extra` and `rejectValue` might seem uncommon at first, it allows you to provide only the types for these you actually need - so for example, if you are not accessing `getState` within your `payloadCreator`, there is no need to provide a type for `state`. The same can be said about `rejectValue` - if you don't need to access any potential error payload, you can ignore it.
659
709
660
-
In addition, you can leverage checks against `action.payload` and `match` as provided by `createAction` as a type-guard for when you want to access known properties on defined types. Example:
As of RTK 1.9, you can define a "pre-typed" version of `createAsyncThunk` that can have the types for `state`, `dispatch`, and `extra` built in. This lets you set up those types once, so you don't have to repeat them each time you call `createAsyncThunk`.
0 commit comments