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

queryOptions.test-d.tsx

379 lines11.2 KB

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