Open History to see the last commit
1import { assertType, describe, expectTypeOf, it } from 'vitest'
2import { queryKey } from '@tanstack/query-test-utils'
3import { QueryClient } from '../queryClient'
4import type { MutationFilters, QueryFilters, Updater } from '../utils'
5import type { Mutation } from '../mutation'
6import type { Query, QueryState } from '../query'
7import type {
8 DataTag,
9 DefaultError,
10 DefaultedQueryObserverOptions,
11 EnsureQueryDataOptions,
12 FetchInfiniteQueryOptions,
13 InfiniteData,
14 MutationOptions,
15 OmitKeyof,
16 QueryKey,
17 QueryObserverOptions,
18} from '../types'
19β
20describe('getQueryData', () => {
21 it('should be typed if key is tagged', () => {
22 const key = ['key'] as DataTag<Array<string>, number>
23 const queryClient = new QueryClient()
24 const data = queryClient.getQueryData(key)
25β
26 expectTypeOf(data).toEqualTypeOf<number | undefined>()
27 })
28β
29 it('should infer unknown if key is not tagged', () => {
30 const key = ['key'] as const
31 const queryClient = new QueryClient()
32 const data = queryClient.getQueryData(key)
33β
34 expectTypeOf(data).toEqualTypeOf<unknown>()
35 })
36β
37 it('should infer passed generic if passed', () => {
38 const key = ['key'] as const
39 const queryClient = new QueryClient()
40 const data = queryClient.getQueryData<number>(key)
41β
42 expectTypeOf(data).toEqualTypeOf<number | undefined>()
43 })
44β
45 it('should only allow Arrays to be passed', () => {
46 assertType<Parameters<QueryClient['getQueryData']>>([
47 // @ts-expect-error TS2345: Argument of type 'string' is not assignable to parameter of type 'QueryKey'
48 { queryKey: 'key' },
49 ])
50 })
51})
52β
53describe('setQueryData', () => {
54 it('updater should be typed if key is tagged', () => {
55 const key = ['key'] as DataTag<Array<string>, number>
56 const queryClient = new QueryClient()
57 const data = queryClient.setQueryData(key, (prev) => {
58 expectTypeOf(prev).toEqualTypeOf<number | undefined>()
59 return prev
60 })
61β
62 expectTypeOf(data).toEqualTypeOf<number | undefined>()
63 })
64β
65 it('value should be typed if key is tagged', () => {
66 const key = ['key'] as DataTag<Array<string>, number>
67 const queryClient = new QueryClient()
68β
69 // @ts-expect-error value should be a number
70 queryClient.setQueryData(key, '1')
71β
72 // @ts-expect-error value should be a number
73 queryClient.setQueryData(key, () => '1')
74β
75 const data = queryClient.setQueryData(key, 1)
76β
77 expectTypeOf(data).toEqualTypeOf<number | undefined>()
78 })
79β
80 it('should infer unknown for updater if key is not tagged', () => {
81 const key = ['key'] as const
82 const queryClient = new QueryClient()
83 const data = queryClient.setQueryData(key, (prev) => {
84 expectTypeOf(prev).toEqualTypeOf<unknown>()
85 return prev
86 })
87β
88 expectTypeOf(data).toEqualTypeOf<unknown>()
89 })
90β
91 it('should infer unknown for value if key is not tagged', () => {
92 const key = ['key'] as const
93 const queryClient = new QueryClient()
94 const data = queryClient.setQueryData(key, 'foo')
95β
96 expectTypeOf(data).toEqualTypeOf<unknown>()
97 })
98β
99 it('should infer passed generic if passed', () => {
100 const key = ['key'] as const
101 const queryClient = new QueryClient()
102 const data = queryClient.setQueryData<string>(key, (prev) => {
103 expectTypeOf(prev).toEqualTypeOf<string | undefined>()
104 return prev
105 })
106β
107 expectTypeOf(data).toEqualTypeOf<string | undefined>()
108 })
109β
110 it('should infer passed generic for value', () => {
111 const key = ['key'] as const
112 const queryClient = new QueryClient()
113 const data = queryClient.setQueryData<string>(key, 'foo')
114β
115 expectTypeOf(data).toEqualTypeOf<string | undefined>()
116 })
117β
118 it('should preserve updater parameter type inference when used in functions with explicit return types', () => {
119 const key = ['key'] as DataTag<Array<string>, number>
120 const queryClient = new QueryClient()
121β
122 // Simulate usage inside a function with explicit return type
123 // The outer function returns 'unknown' but this shouldn't affect the updater's type inference
124 ;(() =>
125 queryClient.setQueryData(key, (data) => {
126 expectTypeOf(data).toEqualTypeOf<number | undefined>()
127 return data
128 })) satisfies () => unknown
129 })
130})
131β
132describe('getQueryState', () => {
133 it('should be loose typed without tag', () => {
134 const key = ['key'] as const
135 const queryClient = new QueryClient()
136 const data = queryClient.getQueryState(key)
137β
138 expectTypeOf(data).toEqualTypeOf<QueryState<unknown, Error> | undefined>()
139 })
140β
141 it('should be typed if key is tagged', () => {
142 const key = ['key'] as DataTag<Array<string>, number>
143 const queryClient = new QueryClient()
144 const data = queryClient.getQueryState(key)
145β
146 expectTypeOf(data).toEqualTypeOf<QueryState<number, Error> | undefined>()
147 })
148β
149 it('should be typed including error if key is tagged', () => {
150 type CustomError = Error & { customError: string }
151 const key = ['key'] as DataTag<Array<string>, number, CustomError>
152 const queryClient = new QueryClient()
153 const data = queryClient.getQueryState(key)
154β
155 expectTypeOf(data).toEqualTypeOf<
156 QueryState<number, CustomError> | undefined
157 >()
158 })
159})
160β
161describe('fetchInfiniteQuery', () => {
162 it('should allow passing pages', async () => {
163 const data = await new QueryClient().fetchInfiniteQuery({
164 queryKey: queryKey(),
165 queryFn: () => Promise.resolve('string'),
166 getNextPageParam: () => 1,
167 initialPageParam: 1,
168 pages: 5,
169 })
170β
171 expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
172 })
173β
174 it('should not allow passing getNextPageParam without pages', () => {
175 assertType<Parameters<QueryClient['fetchInfiniteQuery']>>([
176 {
177 queryKey: ['key'],
178 queryFn: () => Promise.resolve('string'),
179 initialPageParam: 1,
180 getNextPageParam: () => 1,
181 },
182 ])
183 })
184β
185 it('should not allow passing pages without getNextPageParam', () => {
186 assertType<Parameters<QueryClient['fetchInfiniteQuery']>>([
187 // @ts-expect-error Property 'getNextPageParam' is missing
188 {
189 queryKey: ['key'],
190 queryFn: () => Promise.resolve('string'),
191 initialPageParam: 1,
192 pages: 5,
193 },
194 ])
195 })
196})
197β
198describe('defaultOptions', () => {
199 it('should have a typed QueryFunctionContext', () => {
200 new QueryClient({
201 defaultOptions: {
202 queries: {
203 queryFn: (context) => {
204 expectTypeOf(context).toEqualTypeOf<{
205 client: QueryClient
206 queryKey: QueryKey
207 meta: Record<string, unknown> | undefined
208 signal: AbortSignal
209 pageParam?: unknown
210 direction?: unknown
211 }>()
212 return Promise.resolve('data')
213 },
214 },
215 },
216 })
217 })
218})
219β
220describe('fully typed usage', () => {
221 it('type-checks various methods with data & error included in the type', async () => {
222 const queryClient = new QueryClient()
223β
224 type TData = { foo: string }
225 type TError = DefaultError & { bar: string }
226β
227 //
228 // Construct typed arguments
229 //
230β
231 const queryOptions: EnsureQueryDataOptions<TData, TError> = {
232 queryKey: ['key'] as any,
233 }
234 const fetchInfiniteQueryOptions: FetchInfiniteQueryOptions<TData, TError> =
235 {
236 queryKey: ['key'] as any,
237 pages: 5,
238 getNextPageParam: (lastPage) => {
239 expectTypeOf(lastPage).toEqualTypeOf<TData>()
240 return 0
241 },
242 initialPageParam: 0,
243 }
244 const mutationOptions: MutationOptions<TData, TError> = {}
245β
246 const queryFilters: QueryFilters<DataTag<QueryKey, TData, TError>> = {
247 predicate(query) {
248 expectTypeOf(query).toEqualTypeOf<
249 Query<unknown, Error, unknown, ReadonlyArray<unknown>>
250 >()
251 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
252 expectTypeOf(query.state.error).toEqualTypeOf<Error | null>()
253 return false
254 },
255 }
256 const filterKey = queryFilters.queryKey!
257β
258 const mutationFilters: MutationFilters<TData, TError> = {
259 predicate(mutation) {
260 expectTypeOf(mutation).toEqualTypeOf<Mutation<TData, TError>>()
261 expectTypeOf(mutation.state.data).toEqualTypeOf<TData | undefined>()
262 expectTypeOf(mutation.state.error).toEqualTypeOf<TError | null>()
263 return false
264 },
265 }
266 const mutationKey = mutationOptions.mutationKey!
267β
268 //
269 // Method type tests
270 //
271β
272 const state = queryClient.getQueryState(filterKey)
273 expectTypeOf(state).toEqualTypeOf<QueryState<TData, TError> | undefined>()
274β
275 const queryData1 = queryClient.getQueryData(filterKey)
276 expectTypeOf(queryData1).toEqualTypeOf<TData | undefined>()
277β
278 const queryData2 = await queryClient.ensureQueryData(queryOptions)
279 expectTypeOf(queryData2).toEqualTypeOf<TData>()
280β
281 const queriesData = queryClient.getQueriesData(queryFilters)
282 expectTypeOf(queriesData).toEqualTypeOf<
283 Array<[ReadonlyArray<unknown>, unknown]>
284 >()
285β
286 // Type the value before passing it: TypeScript 5.4's `NoInfer` can't match
287 // an inline object literal against the value branch of the `Updater` union
288 // here, so it falls back to the function branch and reports the literal as
289 // excess properties. Annotating sidesteps that (TS >= 5.5 handles it).
290 const newData: TData = { foo: '' }
291 const queryData3 = queryClient.setQueryData(filterKey, newData)
292 type SetQueryDataUpdaterArg = Parameters<
293 typeof queryClient.setQueryData<unknown, typeof filterKey>
294 >[1]
295β
296 expectTypeOf<SetQueryDataUpdaterArg>().toEqualTypeOf<
297 Updater<TData | undefined, TData | undefined>
298 >()
299 expectTypeOf(queryData3).toEqualTypeOf<TData | undefined>()
300β
301 const queriesData2 = queryClient.setQueriesData(queryFilters, { foo: '' }) // TODO: types here are wrong and coming up undefined
302 type SetQueriesDataUpdaterArg = Parameters<
303 typeof queryClient.setQueriesData<unknown, typeof queryFilters>
304 >[1]
305β
306 expectTypeOf<SetQueriesDataUpdaterArg>().toEqualTypeOf<
307 Updater<unknown, unknown>
308 >()
309 expectTypeOf(queriesData2).toEqualTypeOf<Array<[QueryKey, unknown]>>()
310β
311 const queryState = queryClient.getQueryState(filterKey)
312 expectTypeOf(queryState).toEqualTypeOf<
313 QueryState<TData, TError> | undefined
314 >()
315β
316 const fetchedQuery = await queryClient.fetchQuery(queryOptions)
317 expectTypeOf(fetchedQuery).toEqualTypeOf<TData>()
318β
319 queryClient.prefetchQuery(queryOptions)
320β
321 const infiniteQuery = await queryClient.fetchInfiniteQuery(
322 fetchInfiniteQueryOptions,
323 )
324 expectTypeOf(infiniteQuery).toEqualTypeOf<InfiniteData<TData, unknown>>()
325β
326 const infiniteQueryData = await queryClient.ensureInfiniteQueryData(
327 fetchInfiniteQueryOptions,
328 )
329 expectTypeOf(infiniteQueryData).toEqualTypeOf<
330 InfiniteData<TData, unknown>
331 >()
332β
333 const defaultQueryOptions = queryClient.defaultQueryOptions(queryOptions)
334 expectTypeOf(defaultQueryOptions).toEqualTypeOf<
335 DefaultedQueryObserverOptions<TData, TError, TData, TData, QueryKey>
336 >()
337β
338 const mutationOptions2 = queryClient.defaultMutationOptions(mutationOptions)
339 expectTypeOf(mutationOptions2).toEqualTypeOf<
340 MutationOptions<TData, TError, void, unknown>
341 >()
342β
343 queryClient.setMutationDefaults(mutationKey, {
344 onSettled(data, error, variables, context) {
345 expectTypeOf(data).toEqualTypeOf<unknown>()
346 expectTypeOf(error).toEqualTypeOf<DefaultError | null>()
347 expectTypeOf(variables).toEqualTypeOf<void>()
348 expectTypeOf(context).toEqualTypeOf<unknown>()
349 },
350 })
351β
352 const queryDefaults = queryClient.getQueryDefaults(filterKey)
353 expectTypeOf(queryDefaults).toEqualTypeOf<
354 OmitKeyof<QueryObserverOptions<any, any, any, any, any>, 'queryKey'>
355 >()
356β
357 // Voids and Untyped returns
358 queryClient.invalidateQueries(queryFilters)
359 queryClient.isFetching(queryFilters)
360 queryClient.isMutating(mutationFilters)
361 queryClient.removeQueries(queryFilters)
362 queryClient.resetQueries(queryFilters)
363 queryClient.cancelQueries(queryFilters)
364 queryClient.invalidateQueries(queryFilters)
365 queryClient.refetchQueries(queryFilters)
366 queryClient.prefetchInfiniteQuery(fetchInfiniteQueryOptions)
367 queryClient.setQueryDefaults(filterKey, {} as any)
368 queryClient.getMutationDefaults(mutationKey)
369 })
370β
371 it('type-checks various methods with untyped arguments', async () => {
372 const queryClient = new QueryClient()
373β
374 //
375 // Construct typed arguments
376 //
377β
378 const queryOptions: EnsureQueryDataOptions = {
379 queryKey: ['key'] as any,
380 }
381 const fetchInfiniteQueryOptions: FetchInfiniteQueryOptions = {
382 queryKey: ['key'] as any,
383 pages: 5,
384 getNextPageParam: (lastPage) => {
385 expectTypeOf(lastPage).toEqualTypeOf<unknown>()
386 return 0
387 },
388 initialPageParam: 0,
389 }
390 const mutationOptions: MutationOptions = {}
391β
392 const queryFilters: QueryFilters = {
393 predicate(query) {
394 expectTypeOf(query).toEqualTypeOf<Query<unknown, DefaultError>>()
395 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
396 expectTypeOf(query.state.error).toEqualTypeOf<DefaultError | null>()
397 return false
398 },
399 }
400 const filterKey = queryFilters.queryKey!
401β
402 const mutationFilters: MutationFilters = {
403 predicate(mutation) {
404 expectTypeOf(mutation).toEqualTypeOf<Mutation>()
405 expectTypeOf(mutation.state.data).toEqualTypeOf<unknown>()
406 expectTypeOf(mutation.state.error).toEqualTypeOf<DefaultError | null>()
407 return false
408 },
409 }
410 const mutationKey = mutationOptions.mutationKey!
411β
412 //
413 // Method type tests
414 //
415β
416 const state = queryClient.getQueryState(filterKey)
417 expectTypeOf(state).toEqualTypeOf<
418 QueryState<unknown, DefaultError> | undefined
419 >()
420β
421 const queryData1 = queryClient.getQueryData(filterKey)
422 expectTypeOf(queryData1).toEqualTypeOf<unknown>()
423β
424 const queryData2 = await queryClient.ensureQueryData(queryOptions)
425 expectTypeOf(queryData2).toEqualTypeOf<unknown>()
426β
427 const queriesData = queryClient.getQueriesData(queryFilters)
428 expectTypeOf(queriesData).toEqualTypeOf<Array<[QueryKey, unknown]>>()
429β
430 const queryData3 = queryClient.setQueryData(filterKey, { foo: '' })
431 type SetQueryDataUpdaterArg = Parameters<
432 typeof queryClient.setQueryData<unknown, typeof filterKey>
433 >[1]
434β
435 expectTypeOf<SetQueryDataUpdaterArg>().toEqualTypeOf<
436 Updater<unknown, unknown>
437 >()
438 expectTypeOf(queryData3).toEqualTypeOf<unknown>()
439β
440 const queriesData2 = queryClient.setQueriesData(queryFilters, { foo: '' }) // TODO: types here are wrong and coming up undefined
441 type SetQueriesDataUpdaterArg = Parameters<
442 typeof queryClient.setQueriesData<unknown, typeof queryFilters>
443 >[1]
444β
445 expectTypeOf<SetQueriesDataUpdaterArg>().toEqualTypeOf<
446 Updater<unknown, unknown>
447 >()
448 expectTypeOf(queriesData2).toEqualTypeOf<Array<[QueryKey, unknown]>>()
449β
450 const queryState = queryClient.getQueryState(filterKey)
451 expectTypeOf(queryState).toEqualTypeOf<
452 QueryState<unknown, DefaultError> | undefined
453 >()
454β
455 const fetchedQuery = await queryClient.fetchQuery(queryOptions)
456 expectTypeOf(fetchedQuery).toEqualTypeOf<unknown>()
457β
458 queryClient.prefetchQuery(queryOptions)
459β
460 const infiniteQuery = await queryClient.fetchInfiniteQuery(
461 fetchInfiniteQueryOptions,
462 )
463 expectTypeOf(infiniteQuery).toEqualTypeOf<InfiniteData<unknown, unknown>>()
464β
465 const infiniteQueryData = await queryClient.ensureInfiniteQueryData(
466 fetchInfiniteQueryOptions,
467 )
468 expectTypeOf(infiniteQueryData).toEqualTypeOf<
469 InfiniteData<unknown, unknown>
470 >()
471β
472 const defaultQueryOptions = queryClient.defaultQueryOptions(queryOptions)
473 expectTypeOf(defaultQueryOptions).toEqualTypeOf<
474 DefaultedQueryObserverOptions<
475 unknown,
476 DefaultError,
477 unknown,
478 unknown,
479 QueryKey
480 >
481 >()
482β
483 const mutationOptions2 = queryClient.defaultMutationOptions(mutationOptions)
484 expectTypeOf(mutationOptions2).toEqualTypeOf<
485 MutationOptions<unknown, DefaultError, void, unknown>
486 >()
487β
488 queryClient.setMutationDefaults(mutationKey, {
489 onSettled(data, error, variables, context) {
490 expectTypeOf(data).toEqualTypeOf<unknown>()
491 expectTypeOf(error).toEqualTypeOf<DefaultError | null>()
492 expectTypeOf(variables).toEqualTypeOf<void>()
493 expectTypeOf(context).toEqualTypeOf<unknown>()
494 },
495 })
496β
497 const queryDefaults = queryClient.getQueryDefaults(filterKey)
498 expectTypeOf(queryDefaults).toEqualTypeOf<
499 OmitKeyof<QueryObserverOptions<any, any, any, any, any>, 'queryKey'>
500 >()
501β
502 // Voids and Untyped returns
503 queryClient.invalidateQueries(queryFilters)
504 queryClient.isFetching(queryFilters)
505 queryClient.isMutating(mutationFilters)
506 queryClient.removeQueries(queryFilters)
507 queryClient.resetQueries(queryFilters)
508 queryClient.cancelQueries(queryFilters)
509 queryClient.invalidateQueries(queryFilters)
510 queryClient.refetchQueries(queryFilters)
511 queryClient.prefetchInfiniteQuery(fetchInfiniteQueryOptions)
512 queryClient.setQueryDefaults(filterKey, {} as any)
513 queryClient.getMutationDefaults(mutationKey)
514 })
515})
516β
517describe('invalidateQueries', () => {
518 it('shows type error when queryKey is a wrong type in invalidateQueries', () => {
519 assertType<Parameters<QueryClient['invalidateQueries']>>([])
520 assertType<Parameters<QueryClient['invalidateQueries']>>([
521 { queryKey: ['1'] },
522 ])
523 assertType<Parameters<QueryClient['invalidateQueries']>>([
524 // @ts-expect-error
525 { queryKey: '1' },
526 ])
527 })
528 it('needs queryKey to be an array (#8684)', () => {
529 assertType<Parameters<QueryClient['invalidateQueries']>>({
530 // @ts-expect-error key is not an array
531 queryKey: { foo: true },
532 })
533 })
534 it('predicate should be typed if key is tagged', () => {
535 const key = ['key'] as DataTag<Array<string>, number>
536 const queryClient = new QueryClient()
537 queryClient.invalidateQueries({
538 queryKey: key,
539 predicate: (query) => {
540 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
541 expectTypeOf(query.queryKey).toEqualTypeOf<QueryKey>()
542 return true
543 },
544 })
545 })
546})
547β
548describe('cancelQueries', () => {
549 it('predicate should be typed if key is tagged', () => {
550 const key = ['key'] as DataTag<Array<string>, number>
551 const queryClient = new QueryClient()
552 queryClient.cancelQueries({
553 queryKey: key,
554 predicate: (query) => {
555 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
556 expectTypeOf(query.queryKey).toEqualTypeOf<QueryKey>()
557 return true
558 },
559 })
560 })
561})
562β
563describe('removeQueries', () => {
564 it('predicate should be typed if key is tagged', () => {
565 const key = ['key'] as DataTag<Array<string>, number>
566 const queryClient = new QueryClient()
567 queryClient.removeQueries({
568 queryKey: key,
569 predicate: (query) => {
570 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
571 expectTypeOf(query.queryKey).toEqualTypeOf<QueryKey>()
572 return true
573 },
574 })
575 })
576})
577β
578describe('refetchQueries', () => {
579 it('predicate should be typed if key is tagged', () => {
580 const key = ['key'] as DataTag<Array<string>, number>
581 const queryClient = new QueryClient()
582 queryClient.refetchQueries({
583 queryKey: key,
584 predicate: (query) => {
585 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
586 expectTypeOf(query.queryKey).toEqualTypeOf<QueryKey>()
587 return true
588 },
589 })
590 })
591})
592β
593describe('resetQueries', () => {
594 it('predicate should be typed if key is tagged', () => {
595 const key = ['key'] as DataTag<Array<string>, number>
596 const queryClient = new QueryClient()
597 queryClient.resetQueries({
598 queryKey: key,
599 predicate: (query) => {
600 expectTypeOf(query.state.data).toEqualTypeOf<unknown>()
601 expectTypeOf(query.queryKey).toEqualTypeOf<QueryKey>()
602 return true
603 },
604 })
605 })
606})
607type SuccessCallback = () => unknown
608it('should infer types correctly with expression body arrow functions', () => {
609 const key = ['key'] as DataTag<Array<string>, number>
610 const queryClient = new QueryClient()
611β
612 // @ts-expect-error
613 const callbackTest: SuccessCallback = () =>
614 queryClient.setQueryData(key, (data) => {
615 expectTypeOf(data).toEqualTypeOf<number | undefined>()
616 return data
617 })
618})
619β
620it('should infer types correctly with block body arrow functions', () => {
621 const key = ['key'] as DataTag<Array<string>, number>
622 const queryClient = new QueryClient()
623β
624 // @ts-expect-error
625 const callbackTest2: SuccessCallback = () => {
626 queryClient.setQueryData(key, (data) => {
627 expectTypeOf(data).toEqualTypeOf<number | undefined>()
628 return data
629 })
630 }
631})