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

queryOptions.test-d.tsx

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