Skip to content

Commit 3a89ec9

Browse files
authored
chore: improve type safety in getQueryData by using generics (#9218)
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<TInferredQueryFnData>(options.queryHash)?.state .data ``` This change leverages the existing generic type parameter `TInferredQueryFnData` already defined in the `getQueryData` signature and `QueryCache#get` method.
1 parent 3e7d715 commit 3a89ec9

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

packages/query-core/src/queryClient.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,8 @@ export class QueryClient {
133133
>(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined {
134134
const options = this.defaultQueryOptions({ queryKey })
135135

136-
return this.#queryCache.get(options.queryHash)?.state.data as
137-
| TInferredQueryFnData
138-
| undefined
136+
return this.#queryCache.get<TInferredQueryFnData>(options.queryHash)?.state
137+
.data
139138
}
140139

141140
ensureQueryData<

0 commit comments

Comments
 (0)