From fd500a40780e54d72bae4ddc76337ab0deb3b832 Mon Sep 17 00:00:00 2001 From: Neef Rehman Date: Fri, 10 Jan 2025 15:47:08 +0000 Subject: [PATCH] feat(types): support typing `QueryKey` and `MutationKey` via `Register` (#8521) * feat(types): support typing QueryKey and MutationKey via Register * ci: apply automated fixes --------- Co-authored-by: Dominik Dorfmeister Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- docs/framework/react/typescript.md | 22 ++++++++++++++++++++++ packages/query-core/src/types.ts | 18 ++++++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/docs/framework/react/typescript.md b/docs/framework/react/typescript.md index cc2249dae0..76d5423365 100644 --- a/docs/framework/react/typescript.md +++ b/docs/framework/react/typescript.md @@ -172,6 +172,28 @@ declare module '@tanstack/react-query' { ``` [//]: # 'TypingMeta' +[//]: # 'TypingQueryAndMutationKeys' + +## Typing query and mutation keys + +### Registering the query and mutation key types + +Also similarly to registering a [global error type](#registering-a-global-error), you can also register a global `QueryKey` and `MutationKey` type. This allows you to provide more structure to your keys, that matches your application's hierarchy, and have them be typed across all of the library's surface area. Note that the registered type must extend the `Array` type, so that your keys remain an array. + +```ts +import '@tanstack/react-query' + +type QueryKey = ['dashboard' | 'marketing', ...ReadonlyArray] + +declare module '@tanstack/react-query' { + interface Register { + queryKey: QueryKey + mutationKey: QueryKey + } +} +``` + +[//]: # 'TypingQueryAndMutationKeys' [//]: # 'TypingQueryOptions' ## Typing Query Options diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index ce139b04d9..5014cfbf1f 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -32,6 +32,8 @@ export interface Register { // defaultError: Error // queryMeta: Record // mutationMeta: Record + // queryKey: ReadonlyArray + // mutationKey: ReadonlyArray } export type DefaultError = Register extends { @@ -40,7 +42,13 @@ export type DefaultError = Register extends { ? TError : Error -export type QueryKey = ReadonlyArray +export type QueryKey = Register extends { + queryKey: infer TQueryKey +} + ? TQueryKey extends Array + ? TQueryKey + : ReadonlyArray + : ReadonlyArray export const dataTagSymbol = Symbol('dataTagSymbol') export type dataTagSymbol = typeof dataTagSymbol @@ -996,7 +1004,13 @@ export type InfiniteQueryObserverResult< | InfiniteQueryObserverLoadingResult | InfiniteQueryObserverPendingResult -export type MutationKey = ReadonlyArray +export type MutationKey = Register extends { + mutationKey: infer TMutationKey +} + ? TMutationKey extends Array + ? TMutationKey + : ReadonlyArray + : ReadonlyArray export type MutationStatus = 'idle' | 'pending' | 'success' | 'error'