diff --git a/.changeset/wise-numbers-double.md b/.changeset/wise-numbers-double.md new file mode 100644 index 0000000000..cd87bca9b1 --- /dev/null +++ b/.changeset/wise-numbers-double.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': patch +--- + +fix: allow partial query keys in `QueryFilters` diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index 03a7aebad3..3aacc61b81 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -1,4 +1,4 @@ -import { describe, expectTypeOf, it } from 'vitest' +import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import type { QueryFilters } from '../utils' import type { DataTag, QueryKey } from '../types' @@ -35,11 +35,36 @@ describe('QueryFilters', () => { } const queryClient = new QueryClient() - const data = queryClient.getQueryData(a.queryKey!) expectTypeOf(data).toEqualTypeOf() const error = queryClient.getQueryState(a.queryKey!)?.error expectTypeOf(error).toEqualTypeOf() }) + + it('should allow a partial query key to be passed', () => { + const filters: QueryFilters = { + queryKey: ['key'], + } + + expectTypeOf(filters.queryKey).toEqualTypeOf< + | undefined + | readonly [] + | ['key'] + | readonly [ + 'key', + { + a: number + b: string + }, + ] + >() + }) + + it('should error on invalid query keys', () => { + assertType>({ + // @ts-expect-error cannot pass invalid query key + queryKey: ['invalid', { a: 1, b: '1' }], + }) + }) }) diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 2b46cc1c74..1be53edd2d 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -16,6 +16,17 @@ import type { FetchOptions, Query } from './query' // TYPES +type DropLast> = T extends readonly [ + ...infer R, + unknown, +] + ? R + : never + +type TuplePrefixes> = T extends readonly [] + ? readonly [] + : TuplePrefixes> | T + export interface QueryFilters { /** * Filter to active queries, inactive queries or all queries @@ -32,7 +43,7 @@ export interface QueryFilters { /** * Include queries matching this query key */ - queryKey?: TQueryKey + queryKey?: TuplePrefixes /** * Include or exclude stale queries */ @@ -62,7 +73,7 @@ export interface MutationFilters< /** * Include mutations matching this mutation key */ - mutationKey?: MutationKey + mutationKey?: TuplePrefixes /** * Filter by mutation status */