-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
test.ts
593 lines (518 loc) 路 18 KB
/
test.ts
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
import {
ReactQueryProviderConfig,
setConsole,
useInfiniteQuery,
useIsFetching,
useMutation,
usePaginatedQuery,
useQuery,
queryCache,
} from 'react-query'
class FooError extends Error {}
function resetErrorBoundaries() {
queryCache.resetErrorBoundaries // $ExpectType () => void
}
function prefetchQuery() {
queryCache.prefetchQuery('queryKey', (key: string) => Promise.resolve())
queryCache.prefetchQuery('queryKey', (key: string) => Promise.resolve(), {
retry: 1,
})
queryCache.prefetchQuery<number, string, FooError>(
'queryKey',
(key: string) =>
Math.random() > 0.5
? Promise.reject(new FooError())
: Promise.resolve(123),
{ onError: a => false },
{ throwOnError: false }
)
queryCache.prefetchQuery('queryKey', (key: string) => Promise.resolve(), {
throwOnError: true,
})
queryCache.prefetchQuery(['queryKey'], (key: string) => Promise.resolve(), {
throwOnError: true,
})
}
function getQueryData() {
queryCache.getQueryData(['queryKey']);
queryCache.getQueryData('queryKey');
queryCache.getQueryData(true);
queryCache.getQueryData((query) => true);
}
function setQueryData() {
queryCache.setQueryData(['queryKey'], ['data']);
queryCache.setQueryData('queryKey', ['data']);
queryCache.setQueryData(true, ['data']);
queryCache.setQueryData((query) => true, ['data']);
}
function getQuery() {
queryCache.getQuery(['queryKey']);
queryCache.getQuery('queryKey');
queryCache.getQuery(true);
queryCache.getQuery((query) => true);
}
function getQueries() {
queryCache.getQueries(['queryKey']);
queryCache.getQueries('queryKey');
queryCache.getQueries(true);
queryCache.getQueries((query) => true);
}
function simpleQuery() {
// Query - simple case
const querySimple = useQuery<string, 'todos'>('todos', () =>
Promise.resolve('test')
)
querySimple.isFetchingMore // $ExpectError
querySimple.fetchMore // $ExpectError
querySimple.canFetchMore // $ExpectType boolean | undefined
querySimple.clear // $ExpectType () => void
querySimple.clear() // $ExpectType void
querySimple.data // $ExpectType string | undefined
querySimple.error // $ExpectType Error | null
querySimple.failureCount // $ExpectType number
querySimple.isError // $ExpectType boolean
querySimple.isFetching // $ExpectType boolean
querySimple.isIdle // $ExpectType boolean
querySimple.isLoading // $ExpectType boolean
querySimple.isStale // $ExpectType boolean
querySimple.isSuccess // $ExpectType boolean
querySimple.markedForGarbageCollection // $ExpectType boolean
querySimple.query // $ExpectType object
querySimple.refetch // $ExpectType ({ throwOnError }?: { throwOnError?: boolean | undefined; } | undefined) => Promise<string>
querySimple.refetch() // $ExpectType Promise<string>
querySimple.status // $ExpectType "idle" | "loading" | "error" | "success"
querySimple.updatedAt // $ExpectType number
}
function queryWithVariables() {
// Query Variables
const param = 'test'
const query = useQuery(['todos', { param }, 10], (key, variables, id) =>
Promise.resolve(variables.param === 'test')
)
query.data // $ExpectType boolean | undefined
query.refetch() // $ExpectType Promise<boolean>
}
function queryWithReadonlyArray() {
useQuery(
['key', 'a'] as const,
async (
key, // $ExpectType "key"
other // $ExpectType "a"
) => key
)
}
function queryKeyArrayOrder() {
// first element in the key must be not null/undefined
useQuery([null, 'a'], async (key, other) => key) // $ExpectError
useQuery([10, 'a'], async (key, other) => key)
useQuery([false, 'a'], async (key, other) => key)
useQuery([{ complex: { obj: 'yes' } }, 'a'], async (key, other) => key)
}
function conditionalQuery(condition: boolean) {
const queryFn1 = (name: string, params: { bar: string }) =>
Promise.resolve(10)
const queryFn2 = () => Promise.resolve('test')
useQuery(() => 'foo', queryFn2, { enabled: condition }) // $ExpectError
// Query with falsey enabled
useQuery(['foo', { bar: 'baz' }], queryFn1, { enabled: condition })
useQuery(['foo', { bar: 'baz' }], queryFn2, { enabled: condition })
useQuery({
queryKey: ['foo', { bar: 'baz' }],
queryFn: queryFn1,
config: { enabled: condition },
})
}
function queryWithoutFn() {
useQuery('key')
useQuery(['key'])
useQuery('key', { suspense: false }) // with QueryOptions
useQuery(['key'], { suspense: false }) // with QueryOptions
useQuery({ queryKey: 'key' })
useQuery({ queryKey: ['key'] })
useQuery({ queryKey: 'key', config: { suspense: false } }) // with QueryOptions
useQuery({ queryKey: ['key'], config: { suspense: false } }) // with QueryOptions
}
function queryWithObjectSyntax(condition: boolean) {
useQuery({
queryKey: ['key'],
queryFn: async (
key // $ExpectType string
) => key,
}).data // $ExpectType string | undefined
useQuery({
queryKey: ['key', 10],
queryFn: async (
key, // $ExpectType string
id // $ExpectType number
) => 'yay!',
}).data // $ExpectType string | undefined
useQuery({
queryKey: 'key',
queryFn: async (
key // $ExpectType "key"
) => 'yay!',
}).data // $ExpectType string | undefined
useQuery({
queryKey: 'key',
queryFn: async (
key // $ExpectType "key"
) => 10,
config: { enabled: condition },
}).data // $ExpectType number | undefined
}
function queryWithNestedKey() {
// Query with nested variabes
const queryNested = useQuery(['key', { nested: { props: [1, 2] } }], (
key, // $ExpectType string
variables // $ExpectType { nested: { props: number[]; }; }
) => Promise.resolve(variables.nested.props[0]))
queryNested.data // $ExpectType number | undefined
}
function queryWithComplexKeysAndVariables() {
useQuery(['key', { a: 1 }, { b: { x: 1 } }, { c: { x: 1 } }], (
key1, // $ExpectType string
key2, // ExpectType { a: number }
var1, // $ExpectType { b: { x: number; }; }
var2 // $ExpectType { c: { x: number; }; }
) =>
Promise.resolve(
key1 === 'key' && key2.a === 1 && var1.b.x === 1 && var2.c.x === 1
)
)
// custom key
const longKey: [string, ...number[]] = ['key', 1, 2, 3, 4, 5]
useQuery(
longKey,
async (
key, // $ExpectType string
...ids // $ExpectType number[]
) => 100
).data // $ExpectType number | undefined
const longVariables = [true, {}, {}, {}] as const
const queryFn = async (key: string, var1: boolean, ...vars: Array<{}>) => 100
useQuery(['key', ...longVariables] as const, queryFn).data // $ExpectType number | undefined
// the following example cannot work properly, as it would require concatenating tuples with infinite tails.
// ts-toolbelt library's `List.Concat` cannot do the job. It would be possible to do with `typescript-tuple` and additional trick.
// useQuery<number, typeof longKey, typeof longVariables>(longKey, longVariables, async (
// key, // $ExpectType string // <-- currently boolean?!
// keyOrVar, // $ExpectType number | boolean // <-- currently object
// ...rest // $ExpectType number | object // <-- currently object[]
// ) => 100).data; // $ExpectType number | undefined
}
function paginatedQuery() {
// Paginated mode
const queryPaginated = usePaginatedQuery(
'key',
() => Promise.resolve({ data: [1, 2, 3], next: true }),
{
refetchInterval: 1000,
}
)
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.data // $ExpectError
// Discriminated union over status
if (queryPaginated.status === 'loading') {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.error // $ExpectType Error | null
}
if (queryPaginated.status === 'error') {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.error // $ExpectType Error
}
if (queryPaginated.status === 'success') {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.error // $ExpectType null
}
// Discriminated union over status flags
if (queryPaginated.isLoading) {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.error // $ExpectType Error | null
}
if (queryPaginated.isError) {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.error // $ExpectType Error
}
if (queryPaginated.isSuccess) {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.error // $ExpectType null
}
}
function paginatedQueryWithObjectSyntax() {
usePaginatedQuery({
queryKey: ['key', { a: 10 }],
queryFn: async (key, { a }) => (key === 'key' && a === 10 ? 'yes' : 'no'),
}).latestData // $ExpectType "yes" | "no" | undefined
usePaginatedQuery({
queryKey: 'key',
queryFn: async key => (key === 'key' ? 'yes' : 'no'),
}).latestData // $ExpectType "yes" | "no" | undefined
usePaginatedQuery({
queryKey: 'key',
queryFn: async key => (key === 'key' ? 'yes' : 'no'),
}).latestData // $ExpectType "yes" | "no" | undefined
}
function simpleInfiniteQuery(condition: boolean) {
async function fetchWithCursor(key: string, cursor?: string) {
return [1, 2, 3]
}
function getFetchMore(last: number[], all: number[][]) {
return last.length ? String(all.length + 1) : false
}
useInfiniteQuery<number[], [string], string>(['key'], fetchWithCursor, {
getFetchMore: (
last, // $ExpectType number[]
all // $ExpectType number[][]
) => 'next',
// type of data in success is the array of results
onSuccess(
data // $ExpectType number[][]
) {},
onSettled(
data, // $ExpectType number[][] | undefined
error // $ExpectType Error | null
) {},
initialData: () =>
condition
? [
[1, 2],
[2, 3],
]
: undefined,
})
useInfiniteQuery(['key'], fetchWithCursor, { getFetchMore })
useInfiniteQuery('key', fetchWithCursor, { getFetchMore })
useInfiniteQuery('key', fetchWithCursor, { getFetchMore })
const infiniteQuery = useInfiniteQuery(['key'], fetchWithCursor, {
getFetchMore,
})
// The next example does not work; the type for cursor does not get inferred.
// useInfiniteQuery(['key'], fetchWithCursor, {
// getFetchMore: (last, all) => 'string',
// });
infiniteQuery.data // $ExpectType number[][]
infiniteQuery.fetchMore() // $ExpectType Promise<number[][]> | undefined
infiniteQuery.fetchMore('next') // $ExpectType Promise<number[][]> | undefined
infiniteQuery.fetchMore('next', { previous: true }) // $ExpectType Promise<number[][]> | undefined
}
function infiniteQueryWithObjectSyntax() {
useInfiniteQuery({
queryKey: ['key', 1],
queryFn: async (key, id, next = 0) => ({ next: next + 1 }),
config: {
getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
},
}).data // $ExpectType { next: number; }[]
useInfiniteQuery({
queryKey: ['key', 1],
queryFn: async (key, id, next = 0) => ({ next: next + 1 }),
config: {
getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
},
}).data // $ExpectType { next: number; }[]
useInfiniteQuery({
queryKey: 'key',
queryFn: async (
key, // $ExpectType "key"
next = 0
) => ({ next: next + 1 }),
config: {
getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
},
}).data // $ExpectType { next: number; }[]
useInfiniteQuery({
queryKey: 'key',
queryFn: async (
key, // $ExpectType "key"
next = 0
) => ({ next: next + 1 }),
config: {
getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
},
}).data // $ExpectType { next: number; }[]
useInfiniteQuery<{ next: number }, string, undefined>({
queryKey: 'key',
}).data // $ExpectType { next: number; }[]
useInfiniteQuery<{ next: number }, [string], undefined>({
queryKey: ['key'],
}).data // $ExpectType { next: number; }[]
}
function log(...args: any[]) {}
// Simple mutation
function simpleMutation() {
const mutation = () => Promise.resolve(['foo', 'bar'])
const [mutate, mutationState] = useMutation(mutation, {
onSuccess(result) {
result // $ExpectType string[]
},
throwOnError: false,
})
mutate()
mutate({ throwOnError: true })
mutate({
throwOnError: true,
onSettled(result, error) {
result // $ExpectType string[] | undefined
error // $ExpectType Error | null
},
onError(
error // $ExpectType Error
) {},
onSuccess(
result // $ExpectType string[]
) {},
})
// Invalid mutatation function
useMutation((arg1: string, arg2: string) => Promise.resolve()) // $ExpectError
useMutation((arg1: string) => null) // $ExpectError
mutationState.data // $ExpectType string[] | undefined
mutationState.error // $ExpectType Error | null | undefined
mutationState.isError // $ExpectType boolean
mutationState.isIdle // $ExpectType boolean
mutationState.isLoading // $ExpectType boolean
mutationState.isSuccess // $ExpectType boolean
mutationState.reset // $ExpectType () => void
mutationState.status // $ExpectType "idle" | "loading" | "error" | "success"
}
function mutationWithVariables() {
// Mutation with variables
const [mutateWithVars] = useMutation(
({ param }: { param: number }) => Promise.resolve(Boolean(param)),
{
useErrorBoundary: true,
onMutate(variables) {
variables // $ExpectType { param: number; }
return { snapshot: variables.param }
},
}
)
mutateWithVars(
{ param: 1 },
{
async onSuccess(data) {
data // $ExpectType boolean
},
}
)
mutateWithVars({ param: 'test' }) // $ExpectError
}
function helpers() {
useIsFetching() // $ExpectType number
setConsole({ log, error: log, warn: log })
}
function globalConfig() {
const globalConfig: ReactQueryProviderConfig = {
queries: {
useErrorBoundary: true,
refetchOnWindowFocus: true,
},
shared: {
suspense: true,
},
mutations: {
throwOnError: true,
useErrorBoundary: true,
onMutate: (variables: unknown) => Promise.resolve(),
onSuccess: (data: unknown, variables: unknown) => undefined,
onError: (err: Error, variables: unknown, snapshotValue: unknown) =>
undefined,
onSettled: (
data: unknown,
error: Error | null,
variables: unknown,
snapshotValue?: unknown
) => undefined,
},
}
}
function dataDiscriminatedUnion() {
// Query Variables
const param = 'test'
const queryResult = useQuery(['todos', { param }], (key, variables) =>
Promise.resolve([param])
)
queryResult.data // $ExpectType string[] | undefined
// Discriminated union over status
if (queryResult.status === 'loading') {
queryResult.data // $ExpectType string[] | undefined
queryResult.error // $ExpectType Error | null
}
if (queryResult.status === 'error') {
// disabled
queryResult.data // $ExpectType string[] | undefined
queryResult.error // $ExpectType Error
}
if (queryResult.status === 'success') {
// disabled
queryResult.data // $ExpectType string[]
queryResult.error // $ExpectType null
}
// Discriminated union over status flags
if (queryResult.isLoading) {
queryResult.data // $ExpectType string[] | undefined
queryResult.error // $ExpectType Error | null
}
if (queryResult.isError) {
// disabled
queryResult.data // $ExpectType string[] | undefined
queryResult.error // $ExpectType Error
}
if (queryResult.isSuccess) {
// disabled
queryResult.data // $ExpectType string[]
queryResult.error // $ExpectType null
}
}
function mutationStatusDiscriminatedUnion() {
const mutation = () => Promise.resolve(['foo', 'bar'])
const [mutate, mutationState] = useMutation(mutation)
mutate()
// enabled
// TODO: handle invalid argument passed to mutationFn
// mutate('arg'); // $ExpectError
mutate('arg') // $ExpectError
mutationState.data // $ExpectType string[] | undefined
// Discriminated union over status
if (mutationState.status === 'idle') {
mutationState.data // $ExpectType undefined
mutationState.error // $ExpectType null
}
if (mutationState.status === 'loading') {
mutationState.data // $ExpectType undefined
// corrected
// mutationState.error; // $ExpectType null
mutationState.error // $ExpectType undefined
}
if (mutationState.status === 'error') {
mutationState.data // $ExpectType undefined
mutationState.error // $ExpectType Error
}
if (mutationState.status === 'success') {
mutationState.data // $ExpectType string[]
mutationState.error // $ExpectType undefined
}
if (mutationState.isIdle) {
mutationState.data // $ExpectType undefined
mutationState.error // $ExpectType null
}
if (mutationState.isLoading) {
mutationState.data // $ExpectType undefined
// corrected
// mutationState.error; // $ExpectType null
mutationState.error // $ExpectType undefined
}
if (mutationState.isError) {
mutationState.data // $ExpectType undefined
mutationState.error // $ExpectType Error
}
if (mutationState.isSuccess) {
mutationState.data // $ExpectType string[]
mutationState.error // $ExpectType undefined
}
}