Open History to see the last commit
1/* eslint-disable @typescript-eslint/require-await */
2import { describe, expectTypeOf, it } from 'vitest'
3import {
4 and,
5 createCollection,
6 createLiveQueryCollection,
7 eq,
8 gt,
9 parseLoadSubsetOptions,
10} from '@tanstack/db'
11import { QueryClient } from '@tanstack/query-core'
12import { z } from 'zod'
13import { queryCollectionOptions } from '../src/query'
14import type {
15 DataTag,
16 QueryFunctionContext,
17 QueryObserverOptions,
18} from '@tanstack/query-core'
19import type {
20 QueryCollectionConfig,
21 QueryCollectionUtils,
22 RefetchFn,
23} from '../src/query'
24import type {
25 DeleteMutationFnParams,
26 InsertMutationFnParams,
27 LoadSubsetOptions,
28 UpdateMutationFnParams,
29} from '@tanstack/db'
30import type { OutputWithVirtual } from '../../db/tests/utils'
31
32describe(`Query collection type resolution tests`, () => {
33 // Define test types
34 type ExplicitType = { id: string; explicit: boolean }
35
36 // Create a mock QueryClient for tests
37 const queryClient = new QueryClient()
38
39 it(`should type supported top-level Query observer options and reject adapter-owned fields`, () => {
40 queryCollectionOptions<ExplicitType>({
41 id: `query-options-types`,
42 queryClient,
43 queryKey: [`query-options-types`],
44 queryFn: () => Promise.resolve([]),
45 getKey: (item) => item.id,
46 refetchOnWindowFocus: true,
47 refetchOnReconnect: true,
48 refetchOnMount: `always`,
49 networkMode: `online`,
50 })
51
52 queryCollectionOptions<ExplicitType>({
53 id: `query-options-subscribed-owned`,
54 queryClient,
55 queryKey: [`query-options-subscribed-owned`],
56 queryFn: () => Promise.resolve([]),
57 getKey: (item) => item.id,
58 // @ts-expect-error Query Collection owns observer subscription lifecycle.
59 subscribed: false,
60 })
61 })
62
63 it(`rejects mutation handler return-value refetch controls`, () => {
64 type Config = QueryCollectionConfig<ExplicitType>
65 const legacyReturn = async () => ({ refetch: false })
66 expectTypeOf(legacyReturn).not.toExtend<NonNullable<Config[`onInsert`]>>()
67 expectTypeOf(legacyReturn).not.toExtend<NonNullable<Config[`onUpdate`]>>()
68 expectTypeOf(legacyReturn).not.toExtend<NonNullable<Config[`onDelete`]>>()
69 })
70
71 it(`should prioritize explicit type in QueryCollectionConfig`, () => {
72 const options = queryCollectionOptions<ExplicitType>({
73 id: `test`,
74 queryClient,
75 queryKey: [`test`],
76 queryFn: () => Promise.resolve([]),
77 getKey: (item) => item.id,
78 })
79
80 // The getKey function should have the resolved type
81 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
82 })
83
84 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
85 const options = queryCollectionOptions<ExplicitType>({
86 id: `test`,
87 queryClient,
88 queryKey: [`test`],
89 queryFn: () => Promise.resolve([]),
90 getKey: (item) => item.id,
91 onInsert: (params) => {
92 // Verify that the mutation value has the correct type
93 expectTypeOf(
94 params.transaction.mutations[0].modified,
95 ).toEqualTypeOf<ExplicitType>()
96 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
97 string | number
98 >()
99 expectTypeOf(
100 params.transaction.mutations[0].collection.utils.refetch,
101 ).toEqualTypeOf<RefetchFn>()
102 // @ts-expect-error Query Collection does not expose Electric acknowledgement helpers
103 params.transaction.mutations[0].collection.utils.awaitTxId(1)
104 return Promise.resolve()
105 },
106 onUpdate: (params) => {
107 // Verify that the mutation value has the correct type
108 expectTypeOf(
109 params.transaction.mutations[0].modified,
110 ).toEqualTypeOf<ExplicitType>()
111 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
112 string | number
113 >()
114 expectTypeOf(
115 params.transaction.mutations[0].collection.utils.refetch,
116 ).toEqualTypeOf<RefetchFn>()
117 return Promise.resolve()
118 },
119 onDelete: (params) => {
120 // Verify that the mutation value has the correct type
121 expectTypeOf(
122 params.transaction.mutations[0].original,
123 ).toEqualTypeOf<ExplicitType>()
124 expectTypeOf(params.transaction.mutations[0].key).toEqualTypeOf<
125 string | number
126 >()
127 expectTypeOf(
128 params.transaction.mutations[0].collection.utils.refetch,
129 ).toEqualTypeOf<RefetchFn>()
130 return Promise.resolve()
131 },
132 })
133
134 // Verify that the handlers are properly typed
135 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
136 [
137 InsertMutationFnParams<
138 ExplicitType,
139 string | number,
140 QueryCollectionUtils<ExplicitType>
141 >,
142 ]
143 >()
144
145 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
146 [
147 UpdateMutationFnParams<
148 ExplicitType,
149 string | number,
150 QueryCollectionUtils<ExplicitType>
151 >,
152 ]
153 >()
154
155 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
156 [
157 DeleteMutationFnParams<
158 ExplicitType,
159 string | number,
160 QueryCollectionUtils<ExplicitType>
161 >,
162 ]
163 >()
164 })
165
166 it(`should create collection with explicit types`, () => {
167 // Define a user type
168 type UserType = {
169 id: string
170 name: string
171 age: number
172 email: string
173 active: boolean
174 }
175
176 // Create query collection options with explicit type
177 const queryOptions = queryCollectionOptions<UserType>({
178 id: `test`,
179 queryClient,
180 queryKey: [`users`],
181 queryFn: () => Promise.resolve([]),
182 getKey: (item) => item.id,
183 })
184
185 // Create a collection using the query options
186 const usersCollection = createCollection(queryOptions)
187
188 // Test that the collection itself has the correct type
189 expectTypeOf(usersCollection.toArray).toMatchTypeOf<
190 Array<OutputWithVirtual<UserType>>
191 >()
192
193 // Test that the getKey function has the correct parameter type
194 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
195 })
196
197 it(`should infer types from Zod schema through query collection options to live query`, () => {
198 // Define a Zod schema for a user with basic field types
199 const userSchema = z.object({
200 id: z.string(),
201 name: z.string(),
202 age: z.number(),
203 email: z.string().email(),
204 active: z.boolean(),
205 })
206
207 type UserType = z.infer<typeof userSchema>
208
209 // Create query collection options with the schema
210 const queryOptions = queryCollectionOptions({
211 queryClient,
212 queryKey: [`users`],
213 queryFn: () => Promise.resolve([] as Array<UserType>),
214 schema: userSchema,
215 getKey: (item) => item.id,
216 })
217
218 // Create a collection using the query options
219 const usersCollection = createCollection(queryOptions)
220
221 // Create a live query collection that uses the users collection
222 const activeUsersQuery = createLiveQueryCollection({
223 query: (q) =>
224 q
225 .from({ user: usersCollection })
226 .where(({ user }) => eq(user.active, true))
227 .select(({ user }) => ({
228 id: user.id,
229 name: user.name,
230 age: user.age,
231 email: user.email,
232 isActive: user.active,
233 })),
234 })
235
236 // Test that the query results have the correct inferred types
237 const results = activeUsersQuery.toArray
238 expectTypeOf(results).toMatchTypeOf<
239 Array<
240 OutputWithVirtual<{
241 id: string
242 name: string
243 age: number
244 email: string
245 isActive: boolean
246 }>
247 >
248 >()
249
250 // Test that the collection itself has the correct type
251 expectTypeOf(usersCollection.toArray).toMatchTypeOf<
252 Array<OutputWithVirtual<UserType>>
253 >()
254
255 // Test that we can access schema-inferred fields in the query with WHERE conditions
256 const ageFilterQuery = createLiveQueryCollection({
257 query: (q) =>
258 q
259 .from({ user: usersCollection })
260 .where(({ user }) => and(eq(user.active, true), gt(user.age, 18)))
261 .select(({ user }) => ({
262 id: user.id,
263 name: user.name,
264 age: user.age,
265 })),
266 })
267
268 const ageFilterResults = ageFilterQuery.toArray
269 expectTypeOf(ageFilterResults).toMatchTypeOf<
270 Array<
271 OutputWithVirtual<{
272 id: string
273 name: string
274 age: number
275 }>
276 >
277 >()
278
279 // Test that the getKey function has the correct parameter type
280 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
281 })
282
283 describe(`QueryFn type inference`, () => {
284 interface TodoType {
285 id: string
286 title: string
287 completed: boolean
288 }
289
290 it(`should infer types from queryFn return type`, () => {
291 const options = queryCollectionOptions({
292 queryClient,
293 queryKey: [`queryfn-inference`],
294 queryFn: async (): Promise<Array<TodoType>> => {
295 return [] as Array<TodoType>
296 },
297 getKey: (item) => item.id,
298 })
299
300 // Should infer TodoType from queryFn
301 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
302 })
303
304 it(`should throw a type error if explicit type does not match the inferred type from the queryFn`, () => {
305 interface UserType {
306 id: string
307 name: string
308 }
309
310 queryCollectionOptions<UserType>({
311 queryClient,
312 queryKey: [`explicit-priority`],
313 // @ts-expect-error – queryFn doesn't match the explicit type
314 queryFn: async (): Promise<Array<TodoType>> => {
315 return [] as Array<TodoType>
316 },
317 getKey: (item) => item.id,
318 })
319 })
320
321 it(`should prioritize schema over queryFn`, () => {
322 const userSchema = z.object({
323 id: z.string(),
324 name: z.string(),
325 email: z.string(),
326 })
327
328 const options = queryCollectionOptions({
329 queryClient,
330 queryKey: [`schema-priority`],
331 queryFn: async (): Promise<Array<z.infer<typeof userSchema>>> => {
332 return [] as Array<z.infer<typeof userSchema>>
333 },
334 schema: userSchema,
335 getKey: (item) => item.id,
336 })
337
338 // Should use schema type, not TodoType from queryFn
339 type ExpectedType = z.infer<typeof userSchema>
340 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
341 })
342
343 it(`should throw an error if schema type doesn't match the queryFn type`, () => {
344 interface UserType {
345 id: string
346 name: string
347 }
348
349 const userSchema = z.object({
350 id: z.string(),
351 name: z.string(),
352 email: z.string(),
353 })
354
355 const options = queryCollectionOptions({
356 queryClient,
357 queryKey: [`schema-priority`],
358 queryFn: async () => {
359 return [] as Array<UserType>
360 },
361 // @ts-expect-error – queryFn doesn't match the schema type
362 schema: userSchema,
363 getKey: (item) => item.id,
364 })
365
366 // Should use schema type, not TodoType from queryFn
367 type ExpectedType = z.infer<typeof userSchema>
368 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
369 })
370
371 it(`should maintain backward compatibility with explicit types`, () => {
372 const options = queryCollectionOptions<TodoType>({
373 queryClient,
374 queryKey: [`backward-compat`],
375 queryFn: async () => [] as Array<TodoType>,
376 getKey: (item) => item.id,
377 })
378
379 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
380 })
381
382 it(`should work with collection creation`, () => {
383 const options = queryCollectionOptions({
384 queryClient,
385 queryKey: [`collection-test`],
386 queryFn: async (): Promise<Array<TodoType>> => {
387 return [] as Array<TodoType>
388 },
389 getKey: (item) => item.id,
390 })
391
392 const collection = createCollection(options)
393 expectTypeOf(collection.toArray).toEqualTypeOf<
394 Array<OutputWithVirtual<TodoType, string>>
395 >()
396 })
397 })
398
399 describe(`select type inference`, () => {
400 it(`queryFn type inference`, () => {
401 const dataSchema = z.object({
402 id: z.string(),
403 name: z.string(),
404 email: z.string(),
405 })
406
407 const options = queryCollectionOptions({
408 queryClient,
409 queryKey: [`x-queryFn-infer`],
410 queryFn: async (): Promise<Array<z.infer<typeof dataSchema>>> => {
411 return [] as Array<z.infer<typeof dataSchema>>
412 },
413 schema: dataSchema,
414 getKey: (item) => item.id,
415 })
416
417 type ExpectedType = z.infer<typeof dataSchema>
418 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
419 })
420
421 it(`should error when queryFn returns wrapped data without select`, () => {
422 const userData = z.object({
423 id: z.string(),
424 name: z.string(),
425 email: z.string(),
426 })
427
428 type UserDataType = z.infer<typeof userData>
429
430 type WrappedResponse = {
431 metadata: string
432 data: Array<UserDataType>
433 }
434
435 queryCollectionOptions({
436 queryClient,
437 queryKey: [`wrapped-no-select`],
438 // @ts-expect-error - queryFn returns wrapped data but no select provided
439 queryFn: (): Promise<WrappedResponse> => {
440 return Promise.resolve({
441 metadata: `example`,
442 data: [],
443 })
444 },
445 // @ts-expect-error - schema type conflicts with queryFn return type
446 schema: userData,
447 // @ts-expect-error - item type is inferred as object due to type mismatch
448 getKey: (item) => item.id,
449 })
450 })
451
452 it(`select properly extracts array from wrapped response`, () => {
453 const userData = z.object({
454 id: z.string(),
455 name: z.string(),
456 email: z.string(),
457 })
458
459 type UserDataType = z.infer<typeof userData>
460
461 type MetaDataType<T> = {
462 metaDataOne: string
463 metaDataTwo: string
464 data: T
465 }
466
467 const metaDataObject: ResponseType = {
468 metaDataOne: `example meta data`,
469 metaDataTwo: `example meta data`,
470 data: [
471 {
472 id: `1`,
473 name: `carter`,
474 email: `c@email.com`,
475 },
476 ],
477 }
478
479 type ResponseType = MetaDataType<Array<UserDataType>>
480
481 const selectUserData = (data: ResponseType) => {
482 return data.data
483 }
484
485 queryCollectionOptions({
486 queryClient,
487 queryKey: [`x-queryFn-infer`],
488 queryFn: async (): Promise<ResponseType> => {
489 return metaDataObject
490 },
491 select: selectUserData,
492 schema: userData,
493 getKey: (item) => item.id,
494 })
495
496 // Should infer ResponseType as select parameter type
497 expectTypeOf(selectUserData).parameters.toEqualTypeOf<[ResponseType]>()
498 })
499
500 /**
501 * Law and source: The public schema-plus-select overload maps the `queryFn`
502 * result through `select` into materialized schema output rows. Collection
503 * mutations still accept schema input. Here, the schema relation is
504 * `createdAt: string` input -> `createdAt: Date` output.
505 *
506 * Production path and checkpoint: Infer options through
507 * `queryCollectionOptions`, create the Collection, then inspect the public
508 * types at compile time.
509 *
510 * Observations: `select` input, output-row keys, delete keys, collection
511 * reads, and mutation inputs. The paired configs are the hostile control:
512 * they differ only in whether `select` returns schema output or input.
513 * Runtime schema parsing and result publication are outside this oracle.
514 */
515 it(`preserves schema output rows selected from a wrapped response`, () => {
516 const rowSchema = z.object({
517 id: z.string(),
518 createdAt: z.string().transform((value) => new Date(value)),
519 })
520
521 type RowInput = z.input<typeof rowSchema>
522 type RowOutput = z.output<typeof rowSchema>
523 type WrappedResponse = {
524 rows: Array<RowOutput>
525 total: number
526 }
527
528 const options = queryCollectionOptions({
529 queryClient,
530 queryKey: [`wrapped-transformed-schema`],
531 queryFn: async (): Promise<WrappedResponse> => ({
532 rows: [{ id: `1`, createdAt: new Date(0) }],
533 total: 1,
534 }),
535 select: (response) => {
536 expectTypeOf(response).toEqualTypeOf<WrappedResponse>()
537 return response.rows
538 },
539 schema: rowSchema,
540 getKey: (item) => item.id,
541 })
542
543 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[RowOutput]>()
544 expectTypeOf(options.getKey).returns.toEqualTypeOf<string>()
545 expectTypeOf(options.utils.writeDelete).parameters.toEqualTypeOf<
546 [string | Array<string>]
547 >()
548
549 const collection = createCollection(options)
550 collection.insert({ id: `2`, createdAt: `2026-09-20T00:00:00.000Z` })
551
552 const selected = collection.get(`1`)
553 if (selected) {
554 expectTypeOf(selected.createdAt).toEqualTypeOf<Date>()
555 }
556
557 // @ts-expect-error schema mutation inputs have not been materialized yet
558 collection.insert({ id: `3`, createdAt: new Date(0) })
559
560 type HostileResponse = {
561 inputRows: Array<RowInput>
562 outputRows: Array<RowOutput>
563 }
564
565 // Keep every option shared so unrelated config errors cannot satisfy the
566 // negative assertion at the public overload.
567 const schemaOutputSelectConfig = {
568 queryClient,
569 queryKey: [`wrapped-schema-output-control`],
570 queryFn: async (): Promise<HostileResponse> => ({
571 inputRows: [{ id: `1`, createdAt: `1970-01-01T00:00:00.000Z` }],
572 outputRows: [{ id: `1`, createdAt: new Date(0) }],
573 }),
574 select: (response: HostileResponse): Array<RowOutput> =>
575 response.outputRows,
576 schema: rowSchema,
577 getKey: (item: RowOutput) => item.id,
578 }
579 queryCollectionOptions(schemaOutputSelectConfig)
580
581 const schemaInputSelectConfig = {
582 ...schemaOutputSelectConfig,
583 select: (response: HostileResponse): Array<RowInput> =>
584 response.inputRows,
585 }
586
587 // @ts-expect-error select must return materialized schema output rows
588 queryCollectionOptions(schemaInputSelectConfig)
589 })
590 })
591
592 describe(`loadSubsetOptions type inference`, () => {
593 interface TestItem {
594 id: string
595 name: string
596 }
597
598 it(`should type loadSubsetOptions as LoadSubsetOptions in queryFn`, () => {
599 const config: QueryCollectionConfig<TestItem> = {
600 id: `loadSubsetTest`,
601 queryClient,
602 queryKey: [`loadSubsetTest`],
603 queryFn: (ctx) => {
604 // Verify that loadSubsetOptions is assignable to LoadSubsetOptions
605 // This ensures it can be used where LoadSubsetOptions is expected
606 expectTypeOf(
607 ctx.meta!.loadSubsetOptions!,
608 ).toExtend<LoadSubsetOptions>()
609 // so that parseLoadSubsetOptions can be called without type errors
610 parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
611 // The fact that this call compiles without errors verifies that
612 // ctx.meta.loadSubsetOptions is typed correctly as LoadSubsetOptions
613 return Promise.resolve([])
614 },
615 getKey: (item) => item.id,
616 syncMode: `on-demand`,
617 }
618
619 const options = queryCollectionOptions(config)
620 createCollection(options)
621 })
622
623 it(`should allow meta to contain additional properties beyond loadSubsetOptions`, () => {
624 const config: QueryCollectionConfig<TestItem> = {
625 id: `loadSubsetTest`,
626 queryClient,
627 queryKey: [`loadSubsetTest`],
628 queryFn: (ctx) => {
629 // Verify that an object with loadSubsetOptions plus other properties
630 // can be assigned to ctx.meta's type. This ensures the type is not too restrictive.
631 const metaWithExtra = {
632 loadSubsetOptions: ctx.meta!.loadSubsetOptions!,
633 customProperty: `test`,
634 anotherProperty: 123,
635 }
636
637 // Test that this object can be assigned to ctx.meta's type
638 // This verifies that ctx.meta allows additional properties beyond loadSubsetOptions
639 const typedMeta: typeof ctx.meta = metaWithExtra
640
641 // Verify the assignment worked (this will fail at compile time if types don't match)
642 expectTypeOf(
643 typedMeta.loadSubsetOptions!,
644 ).toExtend<LoadSubsetOptions>()
645
646 return Promise.resolve([])
647 },
648 getKey: (item) => item.id,
649 syncMode: `on-demand`,
650 }
651
652 const options = queryCollectionOptions(config)
653 createCollection(options)
654 })
655
656 it(`should have loadSubsetOptions typed automatically without explicit QueryCollectionMeta import`, () => {
657 // This test validates that the module augmentation works automatically
658 // Note: We are NOT importing QueryCollectionMeta, yet ctx.meta.loadSubsetOptions
659 // should still be properly typed as LoadSubsetOptions
660 const config: QueryCollectionConfig<TestItem> = {
661 id: `autoTypeTest`,
662 queryClient,
663 queryKey: [`autoTypeTest`],
664 queryFn: (ctx) => {
665 // This should compile without errors because the module augmentation
666 // in global.d.ts is automatically loaded via the triple-slash reference
667 // in index.ts
668 const options = ctx.meta?.loadSubsetOptions
669
670 // Verify the type is correct
671 expectTypeOf(options).toMatchTypeOf<LoadSubsetOptions | undefined>()
672
673 // Verify it can be passed to parseLoadSubsetOptions without type errors
674 const parsed = parseLoadSubsetOptions(options)
675 expectTypeOf(parsed).toMatchTypeOf<{
676 filters: Array<any>
677 sorts: Array<any>
678 limit?: number
679 }>()
680
681 return Promise.resolve([])
682 },
683 getKey: (item) => item.id,
684 syncMode: `on-demand`,
685 }
686
687 const options = queryCollectionOptions(config)
688 createCollection(options)
689 })
690
691 it(`should allow users to extend QueryCollectionMeta via module augmentation`, () => {
692 // This test validates that users can extend QueryCollectionMeta to add custom properties
693 // by augmenting the @tanstack/query-db-collection module
694
695 // In reality, users would do:
696 // declare module "@tanstack/query-db-collection" {
697 // interface QueryCollectionMeta {
698 // customUserId: number
699 // customContext?: string
700 // }
701 // }
702
703 const config: QueryCollectionConfig<TestItem> = {
704 id: `extendMetaTest`,
705 queryClient,
706 queryKey: [`extendMetaTest`],
707 queryFn: (ctx) => {
708 // ctx.meta still has loadSubsetOptions
709 expectTypeOf(ctx.meta?.loadSubsetOptions).toMatchTypeOf<
710 LoadSubsetOptions | undefined
711 >()
712
713 // This test documents the extension pattern even though we can't
714 // actually augment QueryCollectionMeta in a test file (it would
715 // affect all other tests in the same compilation unit)
716
717 return Promise.resolve([])
718 },
719 getKey: (item) => item.id,
720 syncMode: `on-demand`,
721 }
722
723 const options = queryCollectionOptions(config)
724 createCollection(options)
725 })
726 })
727
728 describe(`queryOptions interoperability`, () => {
729 type NumberItem = {
730 id: number
731 value: string
732 }
733 type TaggedNumbersKey = DataTag<Array<string>, Array<NumberItem>, Error>
734 type NumberQueryObserverOptions = QueryObserverOptions<
735 Array<NumberItem>,
736 Error,
737 Array<NumberItem>,
738 Array<NumberItem>,
739 TaggedNumbersKey
740 >
741 const taggedNumbersQueryKey = [
742 `query-options-numbers`,
743 ] as unknown as TaggedNumbersKey
744
745 it(`should accept queryOptions-like spread config with tagged queryKey`, () => {
746 const queryOptionsLike = {
747 queryKey: taggedNumbersQueryKey,
748 queryFn: () =>
749 Promise.resolve([
750 { id: 1, value: `one` },
751 { id: 2, value: `two` },
752 ]),
753 } satisfies {
754 queryKey: TaggedNumbersKey
755 queryFn?: NumberQueryObserverOptions[`queryFn`]
756 }
757
758 const options = queryCollectionOptions({
759 ...queryOptionsLike,
760 queryClient,
761 getKey: (item) => item.id,
762 })
763
764 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
765 })
766
767 it(`should accept enabled from queryOptions-like config`, () => {
768 const queryOptionsLike = {
769 queryKey: taggedNumbersQueryKey,
770 queryFn: () => Promise.resolve([{ id: 1, value: `one` }]),
771 enabled: (_query) => true,
772 } satisfies {
773 queryKey: TaggedNumbersKey
774 queryFn?: NumberQueryObserverOptions[`queryFn`]
775 enabled?: NumberQueryObserverOptions[`enabled`]
776 }
777
778 const options = queryCollectionOptions({
779 ...queryOptionsLike,
780 queryClient,
781 getKey: (item) => item.id,
782 })
783
784 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
785 })
786
787 it(`should require explicit queryFn when source type marks queryFn optional`, () => {
788 const queryOptionsLike: {
789 queryKey: TaggedNumbersKey
790 queryFn?: (
791 context: QueryFunctionContext<TaggedNumbersKey>,
792 ) => Array<NumberItem> | Promise<Array<NumberItem>>
793 } = {
794 queryKey: taggedNumbersQueryKey,
795 queryFn: () => Promise.resolve([{ id: 1, value: `one` }]),
796 }
797
798 // @ts-expect-error - interop configs require queryFn even when source type marks it optional
799 queryCollectionOptions({
800 ...queryOptionsLike,
801 queryClient,
802 getKey: (item) => item.id,
803 })
804
805 const options = queryCollectionOptions({
806 ...queryOptionsLike,
807 queryFn: (context) => queryOptionsLike.queryFn!(context),
808 queryClient,
809 getKey: (item) => item.id,
810 })
811
812 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
813 })
814
815 it(`should require select for wrapped queryOptions-like responses`, () => {
816 type WrappedResponse = {
817 total: number
818 items: Array<NumberItem>
819 }
820 type TaggedWrappedKey = DataTag<Array<string>, WrappedResponse, Error>
821 type WrappedObserverOptions = QueryObserverOptions<
822 WrappedResponse,
823 Error,
824 WrappedResponse,
825 WrappedResponse,
826 TaggedWrappedKey
827 >
828 const taggedWrappedQueryKey = [
829 `query-options-wrapped`,
830 ] as unknown as TaggedWrappedKey
831
832 const wrappedQueryOptionsLike = {
833 queryKey: taggedWrappedQueryKey,
834 queryFn: () =>
835 Promise.resolve({
836 total: 1,
837 items: [{ id: 1, value: `one` }],
838 }),
839 } satisfies {
840 queryKey: TaggedWrappedKey
841 queryFn?: WrappedObserverOptions[`queryFn`]
842 }
843
844 // @ts-expect-error - wrapped response requires select to extract the item array
845 queryCollectionOptions({
846 ...wrappedQueryOptionsLike,
847 queryClient,
848 getKey: () => 1,
849 })
850
851 const options = queryCollectionOptions({
852 ...wrappedQueryOptionsLike,
853 select: (response) => response.items,
854 queryClient,
855 getKey: (item) => item.id,
856 })
857
858 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
859 })
860
861 it(`should still require queryFn for plain configs`, () => {
862 // @ts-expect-error - queryFn is required for plain configs
863 queryCollectionOptions<NumberItem>({
864 queryClient,
865 queryKey: [`query-options-missing-query-fn`],
866 getKey: (item) => item.id,
867 })
868 })
869
870 it(`should accept synchronous queryFn return values`, () => {
871 const options = queryCollectionOptions<NumberItem>({
872 queryClient,
873 queryKey: [`query-options-sync-query-fn`],
874 queryFn: () => [{ id: 1, value: `one` }],
875 getKey: (item) => item.id,
876 })
877
878 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
879 })
880 })
881
882 it(`should type collection.utils as QueryCollectionUtils after createCollection`, () => {
883 const collection = createCollection(
884 queryCollectionOptions<ExplicitType>({
885 id: `test-utils-typing`,
886 queryClient,
887 queryKey: [`test-utils`],
888 queryFn: () => Promise.resolve([]),
889 getKey: (item) => item.id,
890 }),
891 )
892
893 // Verify that collection.utils is typed as QueryCollectionUtils, not UtilsRecord
894 const utils: QueryCollectionUtils<ExplicitType> = collection.utils
895 expectTypeOf(utils.refetch).toBeFunction()
896 expectTypeOf(collection.utils.refetch).toBeFunction()
897 expectTypeOf(collection.utils.writeInsert).toBeFunction()
898 expectTypeOf(collection.utils.writeUpdate).toBeFunction()
899 expectTypeOf(collection.utils.writeDelete).toBeFunction()
900 expectTypeOf(collection.utils.isFetching).toBeBoolean()
901 expectTypeOf(collection.utils.isLoading).toBeBoolean()
902 expectTypeOf(collection.utils.fetchStatus).toEqualTypeOf<
903 `fetching` | `paused` | `idle`
904 >()
905 })
906})