forked from reduxjs/redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreateAsyncThunk.typetest.ts
More file actions
368 lines (328 loc) · 10.7 KB
/
createAsyncThunk.typetest.ts
File metadata and controls
368 lines (328 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/* eslint-disable no-lone-blocks */
import { createAsyncThunk, Dispatch, createReducer, AnyAction } from 'src'
import { ThunkDispatch } from 'redux-thunk'
import { unwrapResult, SerializedError } from 'src/createAsyncThunk'
import apiRequest, { AxiosError } from 'axios'
import { IsAny, IsUnknown } from 'src/tsHelpers'
function expectType<T>(t: T) {
return t
}
const defaultDispatch = (() => {}) as ThunkDispatch<{}, any, AnyAction>
// basic usage
;(async function() {
const async = createAsyncThunk('test', (id: number) =>
Promise.resolve(id * 2)
)
const reducer = createReducer({}, builder =>
builder
.addCase(async.pending, (_, action) => {
expectType<ReturnType<typeof async['pending']>>(action)
})
.addCase(async.fulfilled, (_, action) => {
expectType<ReturnType<typeof async['fulfilled']>>(action)
expectType<number>(action.payload)
})
.addCase(async.rejected, (_, action) => {
expectType<ReturnType<typeof async['rejected']>>(action)
expectType<Partial<Error> | undefined>(action.error)
})
)
const promise = defaultDispatch(async(3))
expectType<string>(promise.requestId)
expectType<number>(promise.arg)
expectType<(reason?: string) => void>(promise.abort)
const result = await promise
if (async.fulfilled.match(result)) {
expectType<ReturnType<typeof async['fulfilled']>>(result)
// @ts-expect-error
expectType<ReturnType<typeof async['rejected']>>(result)
} else {
expectType<ReturnType<typeof async['rejected']>>(result)
// @ts-expect-error
expectType<ReturnType<typeof async['fulfilled']>>(result)
}
promise
.then(unwrapResult)
.then(result => {
expectType<number>(result)
// @ts-expect-error
expectType<Error>(result)
})
.catch(error => {
// catch is always any-typed, nothing we can do here
})
})()
// More complex usage of thunk args
;(async function() {
interface BookModel {
id: string
title: string
}
type BooksState = BookModel[]
const fakeBooks: BookModel[] = [
{ id: 'b', title: 'Second' },
{ id: 'a', title: 'First' }
]
const correctDispatch = (() => {}) as ThunkDispatch<
BookModel[],
{ userAPI: Function },
AnyAction
>
// Verify that the the first type args to createAsyncThunk line up right
const fetchBooksTAC = createAsyncThunk<
BookModel[],
number,
{
state: BooksState
extra: { userAPI: Function }
}
>(
'books/fetch',
async (arg, { getState, dispatch, extra, requestId, signal }) => {
const state = getState()
expectType<number>(arg)
expectType<BookModel[]>(state)
expectType<{ userAPI: Function }>(extra)
return fakeBooks
}
)
correctDispatch(fetchBooksTAC(1))
// @ts-expect-error
defaultDispatch(fetchBooksTAC(1))
})()
/**
* returning a rejected action from the promise creator is possible
*/
;(async () => {
type ReturnValue = { data: 'success' }
type RejectValue = { data: 'error' }
const fetchBooksTAC = createAsyncThunk<
ReturnValue,
number,
{
rejectValue: RejectValue
}
>('books/fetch', async (arg, { rejectWithValue }) => {
return rejectWithValue({ data: 'error' })
})
const returned = await defaultDispatch(fetchBooksTAC(1))
if (fetchBooksTAC.rejected.match(returned)) {
expectType<undefined | RejectValue>(returned.payload)
expectType<RejectValue>(returned.payload!)
} else {
expectType<ReturnValue>(returned.payload)
}
expectType<ReturnValue>(unwrapResult(returned))
// @ts-expect-error
expectType<RejectValue>(unwrapResult(returned))
})()
{
interface Item {
name: string
}
interface ErrorFromServer {
error: string
}
interface CallsResponse {
data: Item[]
}
const fetchLiveCallsError = createAsyncThunk<
Item[],
string,
{
rejectValue: ErrorFromServer
}
>('calls/fetchLiveCalls', async (organizationId, { rejectWithValue }) => {
try {
const result = await apiRequest.get<CallsResponse>(
`organizations/${organizationId}/calls/live/iwill404`
)
return result.data.data
} catch (err) {
let error: AxiosError<ErrorFromServer> = err // cast for access to AxiosError properties
if (!error.response) {
// let it be handled as any other unknown error
throw err
}
return rejectWithValue(error.response && error.response.data)
}
})
defaultDispatch(fetchLiveCallsError('asd')).then(result => {
if (fetchLiveCallsError.fulfilled.match(result)) {
//success
expectType<ReturnType<typeof fetchLiveCallsError['fulfilled']>>(result)
expectType<Item[]>(result.payload)
} else {
expectType<ReturnType<typeof fetchLiveCallsError['rejected']>>(result)
if (result.payload) {
// rejected with value
expectType<ErrorFromServer>(result.payload)
} else {
// rejected by throw
expectType<undefined>(result.payload)
expectType<SerializedError>(result.error)
// @ts-expect-error
expectType<IsAny<typeof result['error'], true, false>>(true)
}
}
defaultDispatch(fetchLiveCallsError('asd'))
.then(result => {
expectType<Item[] | ErrorFromServer | undefined>(result.payload)
// @ts-expect-error
expectType<Item[]>(unwrapped)
return result
})
.then(unwrapResult)
.then(unwrapped => {
expectType<Item[]>(unwrapped)
// @ts-expect-error
expectType<ErrorFromServer>(unwrapResult(unwrapped))
})
})
}
/**
* payloadCreator first argument type has impact on asyncThunk argument
*/
{
// no argument: asyncThunk has no argument
{
const asyncThunk = createAsyncThunk('test', () => 0)
expectType<() => any>(asyncThunk)
// we have to allow anything to be passed in in this case, to allow
// for compatibility with allowJs & checkJS
asyncThunk(0 as any)
}
// one argument, specified as undefined: asyncThunk has no argument
{
const asyncThunk = createAsyncThunk('test', (arg: undefined) => 0)
expectType<() => any>(asyncThunk)
// @ts-expect-error cannot be called with an argument
asyncThunk(0 as any)
}
// one argument, specified as void: asyncThunk has no argument
{
const asyncThunk = createAsyncThunk('test', (arg: void) => 0)
expectType<() => any>(asyncThunk)
// @ts-expect-error cannot be called with an argument
asyncThunk(0 as any)
}
// one argument, specified as optional number: asyncThunk has optional number argument
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behaviour or it will make arguments optional everywhere
{
const asyncThunk = createAsyncThunk('test', (arg?: number) => 0)
expectType<(arg?: number) => any>(asyncThunk)
asyncThunk()
asyncThunk(5)
// @ts-expect-error
asyncThunk('string')
}
// one argument, specified as number|undefined: asyncThunk has optional number argument
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behaviour or it will make arguments optional everywhere
{
const asyncThunk = createAsyncThunk('test', (arg: number | undefined) => 0)
expectType<(arg?: number) => any>(asyncThunk)
asyncThunk()
asyncThunk(5)
// @ts-expect-error
asyncThunk('string')
}
// one argument, specified as number|void: asyncThunk has optional number argument
{
const asyncThunk = createAsyncThunk('test', (arg: number | void) => 0)
expectType<(arg?: number) => any>(asyncThunk)
asyncThunk()
asyncThunk(5)
// @ts-expect-error
asyncThunk('string')
}
// one argument, specified as any: asyncThunk has required any argument
{
const asyncThunk = createAsyncThunk('test', (arg: any) => 0)
expectType<IsAny<Parameters<typeof asyncThunk>[0], true, false>>(true)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
// one argument, specified as unknown: asyncThunk has required unknown argument
{
const asyncThunk = createAsyncThunk('test', (arg: unknown) => 0)
expectType<IsUnknown<Parameters<typeof asyncThunk>[0], true, false>>(true)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
// one argument, specified as number: asyncThunk has required number argument
{
const asyncThunk = createAsyncThunk('test', (arg: number) => 0)
expectType<(arg: number) => any>(asyncThunk)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
// two arguments, first specified as undefined: asyncThunk has no argument
{
const asyncThunk = createAsyncThunk('test', (arg: undefined, thunkApi) => 0)
expectType<() => any>(asyncThunk)
// @ts-expect-error cannot be called with an argument
asyncThunk(0 as any)
}
// two arguments, first specified as void: asyncThunk has no argument
{
const asyncThunk = createAsyncThunk('test', (arg: void, thunkApi) => 0)
expectType<() => any>(asyncThunk)
// @ts-expect-error cannot be called with an argument
asyncThunk(0 as any)
}
// two arguments, first specified as number|undefined: asyncThunk has optional number argument
// this test will fail with strictNullChecks: false, that is to be expected
// in that case, we have to forbid this behaviour or it will make arguments optional everywhere
{
const asyncThunk = createAsyncThunk(
'test',
(arg: number | undefined, thunkApi) => 0
)
expectType<(arg?: number) => any>(asyncThunk)
asyncThunk()
asyncThunk(5)
// @ts-expect-error
asyncThunk('string')
}
// two arguments, first specified as number|void: asyncThunk has optional number argument
{
const asyncThunk = createAsyncThunk(
'test',
(arg: number | void, thunkApi) => 0
)
expectType<(arg?: number) => any>(asyncThunk)
asyncThunk()
asyncThunk(5)
// @ts-expect-error
asyncThunk('string')
}
// two arguments, first specified as any: asyncThunk has required any argument
{
const asyncThunk = createAsyncThunk('test', (arg: any, thunkApi) => 0)
expectType<IsAny<Parameters<typeof asyncThunk>[0], true, false>>(true)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
// two arguments, first specified as unknown: asyncThunk has required unknown argument
{
const asyncThunk = createAsyncThunk('test', (arg: unknown, thunkApi) => 0)
expectType<IsUnknown<Parameters<typeof asyncThunk>[0], true, false>>(true)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
// two arguments, first specified as number: asyncThunk has required number argument
{
const asyncThunk = createAsyncThunk('test', (arg: number, thunkApi) => 0)
expectType<(arg: number) => any>(asyncThunk)
asyncThunk(5)
// @ts-expect-error
asyncThunk()
}
}