From 1b78c8b0e55ae870f683b870490141b52c901179 Mon Sep 17 00:00:00 2001 From: Braden Wong <13159333+braden-w@users.noreply.github.com> Date: Thu, 29 May 2025 11:01:10 -0700 Subject: [PATCH] refactor: improve type safety in `getQueryData` by using generics Refactored the `getQueryData` method in `QueryClient` to use generics for type inference instead of type assertion with `as`. The previous implementation of `getQueryData` relied on a type assertion (`as`) to cast the result of `queryCache.get()`: ```typescript return this.#queryCache.get(options.queryHash)?.state.data as | TInferredQueryFnData | undefined ``` While this works, using generics is a more type-safe and idiomatic approach in TypeScript. It allows the type system to infer the correct type for `TInferredQueryFnData` when `queryCache.get` is called, reducing the need for manual type casting and potential runtime errors if the cast is incorrect. ## Changes The `getQueryData` method has been updated to pass `TInferredQueryFnData` as a generic type argument to `this.#queryCache.get()`: **Before:** ```typescript return this.#queryCache.get(options.queryHash)?.state.data as | TInferredQueryFnData | undefined ``` **After:** ```typescript return this.#queryCache.get(options.queryHash)?.state .data ``` This change leverages the existing generic type parameter `TInferredQueryFnData` already defined in the `getQueryData` signature and `QueryCache#get` method. --- packages/query-core/src/queryClient.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 650d3e5ad6..5154ecb535 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -133,9 +133,8 @@ export class QueryClient { >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined { const options = this.defaultQueryOptions({ queryKey }) - return this.#queryCache.get(options.queryHash)?.state.data as - | TInferredQueryFnData - | undefined + return this.#queryCache.get(options.queryHash)?.state + .data } ensureQueryData<