forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.ts
447 lines (397 loc) · 13.2 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
import {
useMutation,
useQuery,
usePaginatedQuery,
useInfiniteQuery,
useIsFetching,
setConsole,
ReactQueryProviderConfig,
} from 'react-query'
function simpleQuery() {
// Query - simple case
const querySimple = useQuery('todos', () => Promise.resolve('test'))
querySimple.data // $ExpectType string | undefined
querySimple.error // $ExpectType unknown
querySimple.isFetching // $ExpectType boolean
querySimple.refetch() // $ExpectType Promise<string>
querySimple.fetchMore // $ExpectError
querySimple.canFetchMore // $ExpectError
querySimple.isFetchingMore // $ExpectError
}
function queryWithVariables() {
// Query Variables
const param = 'test'
const queryVariables = useQuery(
['todos', { param }, 10],
(key, variables, id) => Promise.resolve(variables.param === 'test')
)
queryVariables.data // $ExpectType boolean | undefined
queryVariables.refetch() // $ExpectType Promise<boolean>
queryVariables.refetch({ force: true }) // $ExpectType Promise<boolean>
}
function invalidSimpleQuery() {
// first element in the key must be a string
useQuery([10, 'a'], async (id, key) => id) // $ExpectError
}
function conditionalQuery(condition: boolean) {
const queryFn1 = (name: string, params: { bar: string }) =>
Promise.resolve(10)
const queryFn2 = () => Promise.resolve('test')
// Query with falsey query key
useQuery(condition && ['foo', { bar: 'baz' }], queryFn1)
useQuery(condition && ['foo', { bar: 'baz' }], queryFn2)
useQuery({
queryKey: condition && ['foo', { bar: 'baz' }],
queryFn: queryFn1,
})
// Query with query key function
useQuery(() => ['foo', { bar: 'baz' }], queryFn1)
useQuery(() => ['foo', { bar: 'baz' }], queryFn2)
}
function queryWithObjectSyntax(condition: boolean) {
useQuery({
queryKey: ['key'],
queryFn: async key => key,
}).data // $ExpectType string | undefined
useQuery({
queryKey: ['key', 10],
variables: [true, 20],
queryFn: async (
key, // $ExpectType string
id, // $ExpectType number
var1, // $ExpectType boolean
var2 // $ExpectType number
) => 'yay!',
}).data // $ExpectType string | undefined
useQuery({
queryKey: 'key',
variables: [true, 20],
queryFn: async (
key, // $ExpectType "key"
var1, // $ExpectType boolean
var2 // $ExpectType number
) => 'yay!',
}).data // $ExpectType string | undefined
useQuery({
queryKey: condition && 'key',
queryFn: async (
key // $ExpectType "key"
) => 10,
}).data // $ExpectType number | undefined
}
function queryWithNestedKey() {
// Query with nested variabes
const queryNested = useQuery(
[
'key',
{
nested: {
props: [1, 2],
},
},
],
(key, variables) => 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: [boolean, ...object[]] = [true, {}]
useQuery(
['key'],
longVariables,
async (
key, // $ExpectType string
var1, // $ExpectType boolean
...vars // $ExpectType object[]
) => 100
).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 unknown
}
if (queryPaginated.status === 'error') {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
queryPaginated.error // $ExpectType unknown
}
if (queryPaginated.status === 'success') {
queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; }
queryPaginated.error // $ExpectType null
}
}
function paginatedQueryWithObjectSyntax(condition: boolean) {
usePaginatedQuery({
queryKey: condition && ['key', { a: 10 }],
variables: [true],
queryFn: async (key, { a }, debug) =>
key === 'key' && a === 10 && debug ? 'yes' : 'no',
}).latestData // $ExpectType "yes" | "no" | undefined
usePaginatedQuery({
queryKey: 'key',
variables: [true],
queryFn: async (key, debug) => (key === 'key' && debug ? 'yes' : 'no'),
}).latestData // $ExpectType "yes" | "no" | undefined
usePaginatedQuery({
queryKey: condition && (() => condition && 'key'),
variables: [10],
queryFn: async (key, level) =>
key === 'key' && level === 10 ? '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 unknown
) {},
initialData: () =>
condition
? [
[1, 2],
[2, 3],
]
: undefined,
})
useInfiniteQuery(['key'], fetchWithCursor, { getFetchMore })
useInfiniteQuery('key', fetchWithCursor, { getFetchMore })
useInfiniteQuery(() => condition && '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
}
function infiniteQueryWithObjectSyntax(condition: boolean) {
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: condition && (() => condition && ['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: condition && (() => condition && ('key' as const)),
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; }[]
}
function log(...args: any[]) {}
function infiniteQueryWithVariables(condition: boolean) {
async function fetchWithCursor2(
key: string,
debuglog?: (...args: any[]) => void,
cursor?: string
) {
if (debuglog) debuglog(key, cursor)
return [1, 2, 3]
}
function getFetchMore(last: number[], all: number[][]) {
return last.length ? String(all.length + 1) : false
}
useInfiniteQuery<
number[],
[string],
[undefined | ((...args: any[]) => void)],
string
>(['key'], [undefined], fetchWithCursor2, {
getFetchMore: (last, all) => 'next',
})
useInfiniteQuery(['key'], [log], fetchWithCursor2, { getFetchMore })
useInfiniteQuery('key', [log], fetchWithCursor2, { getFetchMore })
useInfiniteQuery(() => condition && 'key', [log], fetchWithCursor2, {
getFetchMore,
})
}
function simpleMutation() {
// Simple mutation
const mutation = () => Promise.resolve(['foo', 'bar'])
const [mutate] = useMutation(mutation, {
onSuccess(result) {
result // $ExpectType string[]
},
})
mutate()
mutate(undefined, {
throwOnError: true,
onSettled(result, error) {
result // $ExpectType string[] | undefined
error // $ExpectType unknown
},
})
// Invalid mutatation funciton
useMutation((arg1: string, arg2: string) => Promise.resolve()) // $ExpectError
useMutation((arg1: string) => null) // $ExpectError
}
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 = {
onError(err, snapshot) {
log('Error', err, snapshot)
},
onMutate(variables) {
log(variables)
},
suspense: true,
isDataEqual: (oldData, newData) => oldData === newData,
}
}
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 unknown
}
if (queryResult.status === 'error') {
// disabled
queryResult.data // $ExpectType string[] | undefined
queryResult.error // $ExpectType unknown
}
if (queryResult.status === 'success') {
// 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 unknown
}
if (mutationState.status === 'success') {
mutationState.data // $ExpectType string[]
mutationState.error // $ExpectType undefined
}
}