v1.3.0-alpha.5
Pre-releaseThis release reworks the createAsyncThunk
types to enable more flexibility in declaring optional generic arguments.
Changes
createAsyncThunk
Generic Types
Per notes in alpha.4
, our original types made it actually impossible to declare the correct State
type for use by getState
in your promise payload creator callback.
We came up with a stopgap solution, but since TS doesn't allow you to specify individual generic arguments by name, it meant that specifying types for some of the thunk options might require specifying all generic types whether you wanted to or not.
Fortunately, @Ethan-Arrowood has found a novel technique for optionally overriding specific generics by name, in a syntax similar to object destructuring, and we've been able to apply that here.
Per the previous example, the most common use case for createAsyncThunk
still does not require specifying any types by hand, as the types for the Returned
value and the thunkArg
argument will be inferred from your payload creator callback:
// basic usage:
const thunk1 = createAsyncThunk("a", async (arg: string) => {
return 42
})
To specify the type of State
, you'll need to specifically declare the types of Returned
and thunkArg
. Then, pass in an object as the third generic argument, and declare the type of a field named state
inside that object:
// specify state type for getState usage
const thunk2 = createAsyncThunk<Promise<number>, string, {state: RootState}>(
"a",
async (arg: string, {getState}) => {
const state = getState();
return 42;
}
)
If you only want to declare the type of the extra
thunk argument, do the same thing, but override the extra
field instead of state
:
interface UserAPI {
fetchUserById: (id: number) => Promise<User>
}
// specify state type for getState usage
const thunk2 = createAsyncThunk<Promise<User>, string, {extra: UserAPI}>(
"a",
async (arg: string, {extra}) => {
const user = await extra.fetchUserById(123)
return user;
}
)
Previously, that would have required also declaring the type of the state
generic, since state
was listed before extra
in the generics definition.
Changelog
- use ThunkApiConfig for optional type arguments (@phryneas , @Ethan-Arrowood - #364)