Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queryOptions.test-d.tsx

387 lines11.8 KB

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