Skip to content

Commit a54b9ff

Browse files
committed
Rework createAsyncThunk types to enable specifying getState type
1 parent cad5bf8 commit a54b9ff

File tree

3 files changed

+41
-6
lines changed

3 files changed

+41
-6
lines changed

src/combinedTest.test.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,9 @@ describe('Combined entity slice', () => {
3636
]
3737

3838
const fetchBooksTAC = createAsyncThunk<
39-
string,
4039
BookModel[],
4140
void,
42-
BaseThunkAPI<{ books: BooksState }, any, Dispatch>
41+
{ books: BooksState }
4342
>(
4443
'books/fetch',
4544
async (arg, { getState, dispatch, extra, requestId, signal }) => {

src/createAsyncThunk.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,16 @@ export const miniSerializeError = (value: any): any => {
5151
* @alpha
5252
*/
5353
export function createAsyncThunk<
54-
ActionType extends string,
5554
Returned,
5655
ThunkArg = void,
56+
State = unknown,
57+
Extra = unknown,
58+
DispatchType extends Dispatch = Dispatch,
59+
ActionType extends string = string,
5760
ThunkAPI extends BaseThunkAPI<any, any, any> = BaseThunkAPI<
58-
unknown,
59-
unknown,
60-
Dispatch
61+
State,
62+
Extra,
63+
DispatchType
6164
>
6265
>(
6366
type: ActionType,

type-tests/files/createAsyncThunk.typetest.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,36 @@ function fn() {}
5555
// catch is always any-typed, nothing we can do here
5656
})
5757
})()
58+
59+
// More complex usage of thunk args
60+
;(async function() {
61+
interface BookModel {
62+
id: string
63+
title: string
64+
}
65+
66+
type BooksState = BookModel[]
67+
68+
const fakeBooks: BookModel[] = [
69+
{ id: 'b', title: 'Second' },
70+
{ id: 'a', title: 'First' }
71+
]
72+
73+
// Verify that the the first type args to createAsyncThunk line up right
74+
const fetchBooksTAC = createAsyncThunk<
75+
BookModel[],
76+
number,
77+
BooksState,
78+
{ userAPI: Function }
79+
>(
80+
'books/fetch',
81+
async (arg, { getState, dispatch, extra, requestId, signal }) => {
82+
const state = getState()
83+
84+
expectType<number>(arg)
85+
expectType<BookModel[]>(state)
86+
expectType<{ userAPI: Function }>(extra)
87+
return fakeBooks
88+
}
89+
)
90+
})()

0 commit comments

Comments
 (0)