[v5 beta] Type inference for `useQuery` breaks when using `queryOptions` util and `select` #5436
Send to my agentDescribe the bug#
When using the new queryOptions util from react-query v5, type inference seems to be a bit fragile. For example when spreading the resulting options object and adding a select statement to the query, the resulting data type is incorrect. More interestingly, the type seems to be inferred correctly if we also set the type refetchInterval option. I haven't tested around exactly which other options trigger this behaviour, but I believe this data point should be helpful enough in fixing the issue.
import { queryOptions } from '@tanstack/react-query'
const options = queryOptions({
queryKey: ["key"],
queryFn: () => Promise.resolve(1),
});
// Type inference breaks, so TS complains about return type of select()
const query1 = useQuery({
...options,
select: (data) => data > 1
});
// Type inference works like it should, so query2.data has type boolean
const query2 = useQuery({
...options,
select: (data) => data > 1,
refetchInterval: 1,
});
// When inlining the query options, types are correct even without refetchInterval
const query3 = useQuery({
queryKey: ["key"],
queryFn: () => Promise.resolve(1),
select: (data) => data > 1,
});
Your minimal, reproducible example#
https://codesandbox.io/p/sandbox/festive-platform-0krnf3?file=%2Fsrc%2FApp.tsx%3A21%2C28
Steps to reproduce#
- Open the codesandbox
- See the ts errors in the editor
Expected behavior#
The correct data type should be inferred from the return type of the select function in useQuery.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
v5.0.0-alpha.34
Tanstack Query adapter#
react-query
TanStack Query version#
v5.0.0-alpha.34
TypeScript version#
v5.0.4
Additional context#
No response
I used custom wrapper around useQuery this providing generic for select which then I would pass to query, so you could easily pass select to custom hooks. It's doable. I want to look into this issue.
it also breaks a simple
intialDatause-case, because the type ofQueryOptionsis inferred asUndefinedInitialDataOptions<number, DefaultError, number, string[]>, and once TS thinksinitialDatais:initialData?: undefined, it doesn't allow us to pass it again ...import { queryOptions, useQuery } from '@tanstack/react-query' // types: alpha const options = queryOptions({ queryKey: ["key"], queryFn: () => Promise.resolve(1), }); const query1 = useQuery({ ...options, initialData: '' // errors here! });it also breaks a simple
intialDatause-case, because the type ofQueryOptionsis inferred asUndefinedInitialDataOptions<number, DefaultError, number, string[]>, and once TS thinksinitialDatais:initialData?: undefined, it doesn't allow us to pass it again ...import { queryOptions, useQuery } from '@tanstack/react-query' // types: alpha const options = queryOptions({ queryKey: ["key"], queryFn: () => Promise.resolve(1), }); const query1 = useQuery({ ...options, initialData: '' // errors here! });That one errors because you're trying to set initialdData to a string while the queryFn returns a number though, right?
That one errors because you're trying to set initialdData to a string while the queryFn returns a number though, right?
you're absolutely right. I thought that the options can't be narrowed anymore once it's set to
UndefinedInitialDataOptions, but seems like they can. Using the right type works, so that's not an issue. Then the question is really: why doesn't the same work for select 🤔I tried to make a custom hook and get on this same issue, any follow ups?
TkDodo added labelsv5
TkDodo added labelsbug
TkDodo added labelstypes
hmm @jakst in a typescript playground, both the one with just
selectand the one withselect+refetchIntervalnow show an error of:Type '(data: number) => boolean' is not assignable to type '(data: number) => number'.(2769)This again makes sense somehow because
optionsis inferred to be:const options: UndefinedInitialDataOptions<number, DefaultError, number, string[]>first generic is return type of the QueryFunction and input to select (
number), and third generic is expected output type of select (number), so a transform tonumber -> booleanis not accepted.I think if you want
select, yourqueryOptionsneed to be a function:const createOptions = <TData = number>(select?: (data: number) => TData) => queryOptions({ queryKey: ["key"], queryFn: () => Promise.resolve(1), select }); const query1 = useQuery({ ...createOptions((data) => data > 1), }); const query2 = useQuery({ ...createOptions((data) => data > 1), refetchInterval: 1, });That's strange. In our repo we have upgraded to Typescript v5.1.3 and react-query v5 alpha-56 since I created the issue, but the types still work like I initially explained. Adding refetchInterval makes the types work the way I would expect them to when using select, while without it select fails.
I would very much like to avoid having to add an intermediary API that might or might not get used every time we use queryOptions. The nice part about the queryOptions API is that it allows only the shared parts of the query to be created up front, while leaving the other options up to the consumer without abstracting over the useQuery hook. Not having this type cooperate unfortunately throws a cog in the whole machinery =(
For
select, which changes the output type, you need a function I'm afraid. The thing withrefetchIntervalis super weird but not reproducible in a standalone typescript playground I guess?No it doesn't seem to work in the TS playground, but I think it's broken in some way.
Try this barebones setup to reproduce:
mkdir tmp && cd tmp npm init --yes npm install typescript @tanstack/react-query@alpha @types/reactPaste this in a typescript file called
tmp.tsand open project in vscodeimport { queryOptions, useQuery } from '@tanstack/react-query' const options = queryOptions({ queryKey: ['key'], queryFn: () => Promise.resolve(1), }) const query1 = useQuery({ ...options, select: (data) => data > 1, }) const query2 = useQuery({ ...options, select: (data) => data > 1, refetchInterval: 1, }) const query3 = useQuery({ queryKey: ['key'], queryFn: () => Promise.resolve(1), select: (data) => data > 1, })query1will have an error on select,query2andquery3will have the correct types without errors.
For select, which changes the output type, you need a function I'm afraid
Yea I see that that's the case at the moment, but it should be possible to write the types in a way that it works, as is evidence by my repro above where it works when refetchInterval is added. Something with the return type of queryOptions is making typescript trip. If a regular
useQuerycall can switch out the type when select is there, why shouldn't one where we spread in queryOptions?If you don't know how to solve this, then I guess there's not much more to do. But please don't dismiss it as not reproducible or impossible to fix 🙏 It really is reproducible if you try my example above.
Thank you for the patience!
Yeah not sure what's up with the ts playground...
But please don't dismiss it as not reproducible or impossible to fix
👍
If a regular useQuery call can switch out the type when select is there, why shouldn't one where we spread in queryOptions?
because a regular
useQueryinfers all the types from what you pass to it. But once you extract it to an object and give it a type, when you spread it, it can become types that don't overlap. Consider, even without thequeryOptionsfunction:import type { UseQueryOptions } from '@tanstack/react-query' const staticOptions: UseQueryOptions<number, Error, number, Array<string>> = { queryKey: ['key'], queryFn: () => Promise.resolve(1), }now you have the 3rd generic (output type) typed to
number. That is whatqueryOptionsis doing under the hood. Now if you spread those, you get the same error:const query3 = useQuery({ ...staticOptions, select: (data) => data > 1, // ^ Type '(data: number) => boolean' is not assignable to type '(data: number) => number'. })because
staticOptionshave definedselectto benumber => number, because of generics 1) and 3).
The real question is: how does
refetchIntervalchange this? The only thing I can see is thatrefetchIntervalcan also be a function that getsdatapassed, and thatdatais of typeTData(3rd generic), so maybe that has something to do with it.I don't have enough understanding of RQ's internal types (or advanced generics in general) to know why the type acts like that, but maybe I can help by showing my current workaround.
All queries in this example get type
UseQueryResult<boolean, DefaultError>, as I would expect. Couldn't the queryOptions type be implemented like this as well?import { useQuery, type UseQueryOptions, type QueryKey } from '@tanstack/react-query' export function createQuery< TParams, const TQueryKey extends QueryKey, TData, TQueryFnData, TError, ReturnType extends UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> >(setupFn: (params: TParams) => ReturnType) { return (params: TParams) => setupFn(params); } const options = createQuery((params: { value: number }) => ({ queryKey: ['key', params.value], queryFn: () => Promise.resolve(params.value * 2), })); const query1 = useQuery({ ...options({value: 1}), select: (data) => data > 1 }); const query2 = useQuery({ ...options({value: 1}), select: (res) => res > 1, refetchInterval: 1, }); const query3 = useQuery({ queryKey: ["key"], queryFn: () => Promise.resolve(1), select: (data) => data > 1, });idk, can you refactor this to not have a
setupFn?Also, what I noticed is that the QueryKey type is not inferred in the QueryFn. It's always
QueryKeyinstead of being inferred from the actualqueryKeythat is passed:@jakst I finally figured out what's wrong in the playground.
@tanstack/react-queryre-exports the Query Core, so when we set// types: beta, it still doesn't pull in the core types of beta.The fix is to explicitly import the core as well, even though it appears unused:
import { queryOptions, useQuery } from '@tanstack/react-query' // types: beta import * as QueryCore from '@tanstack/query-core' // types: betaWith this, I can reproduce your original issue:
TkDodo changed the title
Ah, that explains it! Makes sense.
About the setupFn, you were correct in that the types weren't actually working as expected, so I haven't managed to create a better util fn myself.
TkDodo closed this
Sign in to join this conversation.
yeah that's interesting. I'd expect
selectto not work in these cases, because the return type ofqueryOptionswill be of type<number, Error, number, QueryKey>. Soselectwants to "change" the 3rd generic, but it can't because it has already been inferred.I'm pretty puzzled why adding
refetchInterval: 1changes something. I mean,refetchIntervalcan be a function as well, and it uses the 3rd generic (TData), too, but I'm unsure how this can change the typings onoptions...maybe @DamianOsipiuk or @ecyrbe have any ideas?