Improve TypeScript support for dynamic queryKey with union types #9682
Replies: 4 comments 1 reply
-
|
Please an immediate possible workaround is what I need for now. |
Beta Was this translation helpful? Give feedback.
-
You can workaround this by providing an explicit type cast. From your reproducible example: import type { EnsureQueryDataOptions } from '@tanstack/react-query';
...
const data = await queryClient.ensureQueryData(queryOptions as EnsureQueryDataOptions);For figuring out where the type mismatch is happening, you might need to add explicit type definitions to the The |
Beta Was this translation helpful? Give feedback.
-
|
|
Beta Was this translation helpful? Give feedback.
-
|
I've created a repository with a simplified, minimalistic example demonstrating how we added full type safety to |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Describe the bug
Indexing a query factory with a union type (
UserType = "company" | "club" | "player" | "supporter") causes TypeScript type mismatches in useQuery, ensureQueryData, getQueryData, and so on. The issue arises becauseentityProfileQueries[userType]returns a union of query options with distinct queryKey types (e.g.,{ userType: "player" }vs.{ userType: "supporter" }), while these utilities expect a single type.The player and supporter queries share
ServerPlayerResponseand a select function, but the error occurs for allUserTypevalues due to the queryKey union.Your minimal, reproducible example
https://stackblitz.com/edit/vitejs-vite-yzi9yarp?file=src%2Floader.ts
Steps to reproduce
In the MRE, the error arises from this line in
src/loader.ts:queryOptionsis underlined with an error, andtypeof datais incorrectly resolving toServerPlayerResponse.Expected behavior
The returned data from
queryClient.ensureQueryData(queryOptions)should be a union of:Noting that userType -
playerandsupporter, share exactly the sameTQueryFnDataandTDatafrom theselectoption, but queryKey differ by{ userType: "player" }vs.{ userType: "supporter" }How often does this bug happen?
Every time
Screenshots or Videos
No response
Platform
Tanstack Query adapter
react-query
TanStack Query version
latest
TypeScript version
latest
Additional context
Affects useQuery, ensureQueryData, getQueryData, and so on.
Beta Was this translation helpful? Give feedback.
All reactions