Skip to content
Source
Sign inSign up
TanStack/query

[v5 beta] Type inference for `useQuery` breaks when using `queryOptions` util and `select` #5436

Send to my agent
Closedjakst(GitHub profile, opens in a new tab) opened this issue 15 comments

Describe 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

  1. yeah that's interesting. I'd expect select to not work in these cases, because the return type of queryOptions will be of type <number, Error, number, QueryKey>. So select wants to "change" the 3rd generic, but it can't because it has already been inferred.

    I'm pretty puzzled why adding refetchInterval: 1 changes something. I mean, refetchInterval can be a function as well, and it uses the 3rd generic (TData), too, but I'm unsure how this can change the typings on options...

    maybe @DamianOsipiuk or @ecyrbe have any ideas?

  2. 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.

  3. TkDodocommented

    it also breaks a simple intialData use-case, because the type of QueryOptions is inferred as UndefinedInitialDataOptions<number, DefaultError, number, string[]>, and once TS thinks initialData is: 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!
    });

    see this playground

  4. it also breaks a simple intialData use-case, because the type of QueryOptions is inferred as UndefinedInitialDataOptions<number, DefaultError, number, string[]>, and once TS thinks initialData is: 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!
    });

    see this playground

    That one errors because you're trying to set initialdData to a string while the queryFn returns a number though, right?

  5. TkDodocommented

    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 🤔

  6. I tried to make a custom hook and get on this same issue, any follow ups?

  7. TkDodo added labelsv5

  8. TkDodo added labelsbug

  9. TkDodo added labelstypes

  10. hmm @jakst in a typescript playground, both the one with just select and the one with select + refetchInterval now show an error of:

    Type '(data: number) => boolean' is not assignable to type '(data: number) => number'.(2769)

    This again makes sense somehow because options is 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 to number -> boolean is not accepted.

    I think if you want select, your queryOptions need 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,
    });

    see this playground

  11. 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 =(

  12. For select, which changes the output type, you need a function I'm afraid. The thing with refetchInterval is super weird but not reproducible in a standalone typescript playground I guess?

  13. 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/react

    Paste this in a typescript file called tmp.ts and open project in vscode

    import { 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,
    })

    query1 will have an error on select, query2 and query3 will 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 useQuery call 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!

  14. TkDodocommented

    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 useQuery infers 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 the queryOptions function:

    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 what queryOptions is 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 staticOptions have defined select to be number => number, because of generics 1) and 3).


    The real question is: how does refetchInterval change this? The only thing I can see is that refetchInterval can also be a function that gets data passed, and that data is of type TData (3rd generic), so maybe that has something to do with it.

  15. 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.

    This TS playground shows a helper function that I created to basically do what I expect queryOptions to do

    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,
    });
  16. 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 QueryKey instead of being inferred from the actual queryKey that is passed:

    playground

  17. TkDodocommented

    @jakst I finally figured out what's wrong in the playground. @tanstack/react-query re-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: beta

    With this, I can reproduce your original issue:

    playground

  18. TkDodo changed the title

  19. 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.

  20. TkDodo closed this

Sign in to join this conversation.