Open History to see the last commit
1import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core'
2import { createKey } from '@tanstack/query-test-utils'
3import { assertType, describe, expectTypeOf, it } from 'vitest'
4import { queryOptions } from '../queryOptions'
5import { useQueries } from '../useQueries'
6import { useQuery } from '../useQuery'
7import { useSuspenseQuery } from '../useSuspenseQuery'
8import type {
9 DataTag,
10 InitialDataFunction,
11 QueryPersister,
12} from '@tanstack/query-core'
13import type { AnyUseQueryOptions } from '../types'
14β
15// Regression test for exported queryOptions inference under declaration emit.
16// TypeScript should be able to name the return type without expanding the
17// internal data tag symbols into the consumer's .d.ts output.
18export const exportedQueryOptions = queryOptions({
19 queryKey: ['invalid'],
20})
21β
22describe('queryOptions', () => {
23 it('should not allow excess properties', () => {
24 assertType(
25 queryOptions({
26 queryKey: createKey(),
27 queryFn: () => Promise.resolve(5),
28 // @ts-expect-error this is a good error, because stallTime does not exist!
29 stallTime: 1000,
30 }),
31 )
32 })
33β
34 it('should infer types for callbacks', () => {
35 queryOptions({
36 queryKey: createKey(),
37 queryFn: () => Promise.resolve(5),
38 staleTime: 1000,
39 select: (data) => {
40 expectTypeOf(data).toEqualTypeOf<number>()
41 },
42 })
43 })
44β
45 it('should work when passed to useQuery', () => {
46 const options = queryOptions({
47 queryKey: createKey(),
48 queryFn: () => Promise.resolve(5),
49 })
50β
51 const { data } = useQuery(options)
52 expectTypeOf(data).toEqualTypeOf<number | undefined>()
53 })
54β
55 it('should work when passed to useSuspenseQuery', () => {
56 const options = queryOptions({
57 queryKey: createKey(),
58 queryFn: () => Promise.resolve(5),
59 })
60β
61 const { data } = useSuspenseQuery(options)
62 expectTypeOf(data).toEqualTypeOf<number>()
63 })
64β
65 it('should work when passed to query', async () => {
66 const options = queryOptions({
67 queryKey: ['key'],
68 queryFn: () => Promise.resolve(5),
69 })
70β
71 const data = await new QueryClient().query(options)
72 expectTypeOf(data).toEqualTypeOf<number>()
73 })
74β
75 it('should work when passed to fetchQuery', async () => {
76 const options = queryOptions({
77 queryKey: createKey(),
78 queryFn: () => Promise.resolve(5),
79 })
80β
81 // oxlint-disable-next-line tanstack-query/no-restricted-syntax -- grandfathered direct test
82 const data = await new QueryClient().fetchQuery(options)
83 expectTypeOf(data).toEqualTypeOf<number>()
84 })
85β
86 it('should work when passed to query with select', async () => {
87 const options = queryOptions({
88 queryKey: ['key'],
89 queryFn: () => Promise.resolve(5),
90 select: (data) => data.toString(),
91 })
92β
93 const data = await new QueryClient().query(options)
94 expectTypeOf(data).toEqualTypeOf<string>()
95 })
96β
97 it('should work when passed to query with enabled: false', async () => {
98 const options = queryOptions({
99 queryKey: ['key'],
100 queryFn: () => Promise.resolve(5),
101 enabled: false,
102 })
103β
104 const data = await new QueryClient().query(options)
105 expectTypeOf(data).toEqualTypeOf<number>()
106 })
107β
108 it('should work when passed to query with skipToken', async () => {
109 const options = queryOptions({
110 queryKey: ['key'],
111 queryFn: skipToken,
112 })
113β
114 const data = await new QueryClient().query(options)
115 expectTypeOf(data).toEqualTypeOf<unknown>()
116 })
117β
118 it('should ignore select when passed to fetchQuery', async () => {
119 const options = queryOptions({
120 queryKey: ['key'],
121 queryFn: () => Promise.resolve(5),
122 select: (data) => data.toString(),
123 })
124β
125 // oxlint-disable-next-line tanstack-query/no-restricted-syntax -- grandfathered direct test
126 const data = await new QueryClient().fetchQuery(options)
127 expectTypeOf(data).toEqualTypeOf<number>()
128 })
129β
130 it('should work when passed to useQueries', () => {
131 const options = queryOptions({
132 queryKey: createKey(),
133 queryFn: () => Promise.resolve(5),
134 })
135β
136 const [{ data }] = useQueries({
137 queries: [options],
138 })
139β
140 expectTypeOf(data).toEqualTypeOf<number | undefined>()
141 })
142β
143 it('should tag the queryKey with the result type of the QueryFn', () => {
144 const { queryKey: tagged } = queryOptions({
145 queryKey: createKey(),
146 queryFn: () => Promise.resolve(5),
147 })
148β
149 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
150 })
151β
152 it('should tag the queryKey even if no promise is returned', () => {
153 const { queryKey: tagged } = queryOptions({
154 queryKey: createKey(),
155 queryFn: () => 5,
156 })
157β
158 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
159 })
160β
161 it('should tag the queryKey with unknown if there is no queryFn', () => {
162 const { queryKey: tagged } = queryOptions({
163 queryKey: createKey(),
164 })
165β
166 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<unknown>()
167 })
168β
169 it('should tag the queryKey with the result type of the QueryFn if select is used', () => {
170 const { queryKey: tagged } = queryOptions({
171 queryKey: createKey(),
172 queryFn: () => Promise.resolve(5),
173 select: (data) => data.toString(),
174 })
175β
176 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
177 })
178β
179 it('should return the proper type when passed to getQueryData', () => {
180 const { queryKey: tagged } = queryOptions({
181 queryKey: createKey(),
182 queryFn: () => Promise.resolve(5),
183 })
184β
185 const queryClient = new QueryClient()
186 const data = queryClient.getQueryData(tagged)
187 expectTypeOf(data).toEqualTypeOf<number | undefined>()
188 })
189β
190 it('should return the proper type when passed to getQueryState', () => {
191 const { queryKey: tagged } = queryOptions({
192 queryKey: createKey(),
193 queryFn: () => Promise.resolve(5),
194 })
195β
196 const queryClient = new QueryClient()
197 const state = queryClient.getQueryState(tagged)
198 expectTypeOf(state?.data).toEqualTypeOf<number | undefined>()
199 })
200β
201 it('should properly type updaterFn when passed to setQueryData', () => {
202 const { queryKey: tagged } = queryOptions({
203 queryKey: createKey(),
204 queryFn: () => Promise.resolve(5),
205 })
206β
207 const queryClient = new QueryClient()
208 const data = queryClient.setQueryData(tagged, (prev) => {
209 expectTypeOf(prev).toEqualTypeOf<number | undefined>()
210 return prev
211 })
212 expectTypeOf(data).toEqualTypeOf<number | undefined>()
213 })
214β
215 it('should preserve discriminated union narrowing in setQueryData updaterFn', () => {
216 type Data =
217 | { kind: 'a'; value: number; requiredA: number }
218 | { kind: 'b'; value: number; requiredB: number }
219β
220 const { queryKey: tagged } = queryOptions({
221 queryKey: createKey(),
222 queryFn: (): Promise<Data> =>
223 Promise.resolve({
224 kind: 'a',
225 value: 1,
226 requiredA: 1,
227 }),
228 })
229β
230 const queryClient = new QueryClient()
231 queryClient.setQueryData(tagged, (prev) => {
232 if (!prev || prev.kind !== 'a') {
233 return prev
234 }
235β
236 expectTypeOf(prev).toEqualTypeOf<Extract<Data, { kind: 'a' }>>()
237 return { ...prev, value: prev.value + 1 }
238 })
239β
240 // @ts-expect-error updater input should be inferred from the tagged query key
241 queryClient.setQueryData(tagged, (prev: string | undefined) => prev)
242 })
243β
244 it('should properly type value when passed to setQueryData', () => {
245 const { queryKey: tagged } = queryOptions({
246 queryKey: createKey(),
247 queryFn: () => Promise.resolve(5),
248 })
249β
250 const queryClient = new QueryClient()
251β
252 // @ts-expect-error value should be a number
253 queryClient.setQueryData(tagged, '5')
254 // @ts-expect-error value should be a number
255 queryClient.setQueryData(tagged, () => '5')
256β
257 const data = queryClient.setQueryData(tagged, 5)
258 expectTypeOf(data).toEqualTypeOf<number | undefined>()
259 })
260β
261 it('should infer even if there is a conditional skipToken', () => {
262 const options = queryOptions({
263 queryKey: createKey(),
264 queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
265 })
266β
267 const queryClient = new QueryClient()
268 const data = queryClient.getQueryData(options.queryKey)
269 expectTypeOf(data).toEqualTypeOf<number | undefined>()
270 })
271β
272 it('should infer to unknown if we disable a query with just a skipToken', () => {
273 const options = queryOptions({
274 queryKey: createKey(),
275 queryFn: skipToken,
276 })
277β
278 const queryClient = new QueryClient()
279 const data = queryClient.getQueryData(options.queryKey)
280 expectTypeOf(data).toEqualTypeOf<unknown>()
281 expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf<unknown>()
282 })
283β
284 it('should throw a type error when using queryFn with skipToken in a suspense query', () => {
285 const options = queryOptions({
286 queryKey: createKey(),
287 queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
288 })
289 // @ts-expect-error TS2345
290 const { data } = useSuspenseQuery(options)
291 expectTypeOf(data).toEqualTypeOf<number>()
292 })
293β
294 it('should allow undefined response in initialData', () => {
295 assertType((id: string | null) =>
296 queryOptions({
297 queryKey: ['todo', id],
298 queryFn: () =>
299 Promise.resolve({
300 id: '1',
301 title: 'Do Laundry',
302 }),
303 initialData: () =>
304 !id
305 ? undefined
306 : {
307 id,
308 title: 'Initial Data',
309 },
310 }),
311 )
312 })
313β
314 it('should allow optional initialData object', () => {
315 const options = queryOptions({
316 queryKey: createKey(),
317 queryFn: () => Promise.resolve('something string'),
318 initialData: Math.random() > 0.5 ? 'initial string' : undefined,
319 })
320β
321 expectTypeOf(options.initialData).toExtend<
322 InitialDataFunction<string> | string | undefined
323 >()
324 })
325β
326 it('should be passable to UseQueryOptions', () => {
327 function somethingWithQueryOptions<TQueryOpts extends AnyUseQueryOptions>(
328 options: TQueryOpts,
329 ) {
330 return options.queryKey
331 }
332β
333 const options = queryOptions({
334 queryKey: createKey(),
335 queryFn: () => Promise.resolve(1),
336 })
337β
338 assertType(somethingWithQueryOptions(options))
339 })
340β
341 it('should return a custom query key type', () => {
342 type MyQueryKey = [Array<string>, { type: 'foo' }]
343β
344 const options = queryOptions({
345 queryKey: [['key'], { type: 'foo' }] as MyQueryKey,
346 queryFn: () => Promise.resolve(1),
347 })
348β
349 expectTypeOf(options.queryKey).toEqualTypeOf<
350 DataTag<MyQueryKey, number, Error>
351 >()
352 })
353β
354 it('should return a custom query key type with datatag', () => {
355 type MyQueryKey = DataTag<
356 [Array<string>, { type: 'foo' }],
357 number,
358 Error & { myMessage: string }
359 >
360β
361 const options = queryOptions({
362 queryKey: [['key'], { type: 'foo' }] as MyQueryKey,
363 queryFn: () => Promise.resolve(1),
364 })
365β
366 expectTypeOf(options.queryKey).toEqualTypeOf<
367 DataTag<MyQueryKey, number, Error & { myMessage: string }>
368 >()
369 })
370β
371 it('should infer TQueryFnData from persister paired with a queryFn declaring a parameter (#7842)', () => {
372 const persister = undefined as unknown as QueryPersister<string, any>
373β
374 const options = queryOptions({
375 queryKey: ['key'],
376 queryFn: (_context) => 'hello',
377 persister,
378 })
379β
380 expectTypeOf(options.queryFn!).returns.toEqualTypeOf<
381 string | Promise<string>
382 >()
383 })
384β
385 it('should still error when persister and queryFn return types genuinely conflict', () => {
386 const persister = undefined as unknown as QueryPersister<string, any>
387β
388 assertType(
389 queryOptions({
390 queryKey: ['key'],
391 // @ts-expect-error persister expects string, queryFn returns number
392 queryFn: () => 42,
393 persister,
394 }),
395 )
396β
397 assertType(
398 queryOptions({
399 queryKey: ['key'],
400 // @ts-expect-error persister expects string, queryFn with arg returns number
401 queryFn: (_context) => 42,
402 persister,
403 }),
404 )
405 })
406})