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