Skip to content
Source
Sign inSign up
TanStack/query

[Vue Query] queryOption type inference broken when using computed queryOption with `select` option #9789

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

Describe the bug

queryOption type inference broken when using computed queryOption with select option

Your minimal, reproducible example

Sorry I couldn't find an existed vue example with tanstack query v5 set up to edit upon. But the steps should be really simple to reproduce

Steps to reproduce

1. Create a dynamic queryOption

const postsByUserIdQueryOption = (userId: string) => queryOption(...)

2. Use the computed queryOption in the component

const { data: posts } = useQuery(computed(() => postsByUserIdQueryOption(userId.value)))

3. Spread the options and add an enabled option - it works ✅

const { data: posts } = useQuery(computed(() => ({
  ...postsByUserIdQueryOption(userId.value),
  enabled: !!userId.value
})))

4. Add a select option - type error occurs ❌

const { data: postCount } = useQuery(computed(() => ({
  ...postsByUserIdQueryOption(userId.value),
  enabled: !!userId.value,
  select: (data) => data.length  // Monstrous typescript error
})))

but this ↓ non-dynamic queryOption without computed will work and postCount is correctly inferred to be a number ✅

const { data: postCount } = useQuery({
  ...postsByUserIdQueryOption(userId.value),
  enabled: !!userId.value,
  select: (data) => data.length  
})

5. Manually type data - fixes the type error ✅

const { data: postCount } = useQuery(computed(() => ({
  ...postsByUserIdQueryOption(userId.value),
  enabled: !!userId.value,
  select: (data: Post[]) => data.length
})))

Here ↓, it will also not infer correctly

const queryOption = computed(() => ({
    ...getPostsByUserIdQueryOption(userId.value)
    enabled: !!userId.value,
    select: (data) => data.length // typescript error here, data can be any, instead of the return type of queryFn defined inside queryOption
}))

Expected behavior

when having something like this

const { data: postCount } = useQuery(computed(() => ({
  ...postsByUserIdQueryOption(userId.value),
  enabled: !!userId.value,
  select: (data) => data.length
})))

the data parameter in select callback should be automatically inferred to the same type as the return type of queryFn provided in queryOption

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

  • vs code
  • vue query v5

Tanstack Query adapter

None

TanStack Query version

v5.83.0

TypeScript version

5.4.5

Additional context

No response

  1. Ran into the same problem any updates , other than that fix and this fix const { data: postCount } = useQuery<Post[])>(computed(() => ({ ...postsByUserIdQueryOption(userId.value), enabled: !!userId.value, select: (data => data.length }))) are you using orpc by any chance ??

  2. I think the type inference can be fixed by adding another queryOptions call. For example:

    //                                 ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
    const queryOption = computed(() => queryOptions({
        ...getPostsByUserIdQueryOption(userId.value)
        enabled: !!userId.value,
        select: (data) => data.length
    }))
  3. @meliuos No I wasn't using orpc, I was using AppSync graphql wrapped in my custom function.

  4. I also struggled with these interfaces and ended up writing my own wrappers around useQuery, useInfiniteQuery, useQueries and useMutation

    I figured out that if you present solid-query-like interface, type inference becomes a lot easier. Is there any chance we can get similar interface in a new major version?

    const { data: postCount } = useQuery(() => ({
        ...getPostsByUserIdQueryOption(userId.value)
        enabled: !!userId.value,
        select: (data) => data.length
    }));

    I could dedicate some time to make a PR, because there are some issues that you can't solve with just wrappers. For example useInfiniteQuery uses mapped type with conditional on "enabled" property and MaybeRefOrGetter/MaybeRefDeep for each options key. I can't just pass a computed of query options to a useInfiniteQuery for some reason. Why are these interfaces different for useQuery/useInfiniteQuery? Same problem with useQueries

    We could get rid of all of these inconsistencies and make interface of these functions better for type inference if we just always accept getter as a parameter for useQuery/useInfiniteQuery/useQueries/useMutation and use this getter inside any reactive context internally, or cache it with wrapping it into computed.

  5. I am also facing a similar issue with type inference when a select option is added, this is on React Query and not Vue Query, but the issues seem very similar, hence i've put a comment a here.

    I have a map of keys -> query options and the query options are computed, some of the options have a select key and the others don't, all of them end up returning the same final data type, but useQuery is not able to infer it

    An example is below:

    import { queryOptions, useQuery } from '@tanstack/react-query'
    
    const opt = {
      hasName: (options: { enabled: boolean; region: string }) => ({
        queryKey: ['A', options.region],
        queryFn: async () => {
          return Promise.resolve({name: "Jackson"}) // fetch data for A
        },
        enabled: options.enabled,
      }),
      hasNameAndId: (options: { enabled: boolean; region: string }) => queryOptions({
        queryKey: ['B', options.region],
        queryFn: async (): Promise<{name: string, id: string}> => {
          return Promise.resolve({name: "Jackson", id: "1234"}) // fetch data for B
        },
        select: (data) => ({ name: data.name, id: data.id }),
        enabled: options.enabled,
      }),
    }
    type SupportedTypes = keyof typeof opt
    
    export function useCustomData(type: SupportedTypes, options: { enabled?: boolean; region?: string } = {}): {name: string} | undefined {
      const { enabled = true, region = 'us' } = options
      const res = useQuery(
        opt[type]({ enabled, region })
      )
      return res.data
    }

    the opt[type] is showing an inference error, despite the fact that both of the query options return the same data type. When it is used with the exact keys like opt['hasName'] or opt['hasNameAndId'] it does not show this compilation issue.

    Please let me know if this is not the appropriate issue for this and if i should create a new one for this.

  6. TkDodocommented

    please show a typescript playground

    @DamianOsipiuk FYI

  7. TkDodo added labelspackage: vue-query

  8. Typescript playground link: click here

    NOTE: This playground is using the react-query package and not the vue-query

  9. okay so it’s not vue related ?

    i think it's occuring in both react and vue

    I get that if i ensure that both the queryFn returns the same type it will be fixed The question that i have is that the data the useQuery() returns for both those queryOptions are the same type. both return just {name: string} due to the presence of the select option in hasNameAndId. If you were to access it directly with hasNameAndId or with hasName it would still compile and return properly, it only has this issue when it's dynamically picking it

    Attaching playground link with direct access instead of dynamic access -> click here

    Note how useCustomData and useCustomData2 have the same signature despite both using different queryFn

  10. TkDodocommented

    both return just {name: string} due to the presence of the select option

    on type level, there are two types for useQuery: One for what the queryFn returns (TQueryFnData) and one for what useQuery itself returns (TData). The default for TData is TQueryFnData, so if you have no select, it’s the same, but if you have select, they can differ.

    So while you get the same thing at runtime, it’s two different things on type level.

    I don’t think there’s a lot we can do here

  11. TkDodo removed labelspackage: vue-query

  12. TkDodo added labelstypes

  13. As I understand original problem raised in this thread is vue-query only.

    I'm not aware of a way to add packages into typescript playground, because of it I made a repro of original vue-query problem on stackblitz https://stackblitz.com/edit/vitejs-vite-fo1j5vbe?file=src%2FApp.data.ts

    main chunk of code

    import { ref, computed } from 'vue';
    import { queryOptions, useQuery } from '@tanstack/vue-query';
    
    const sleep = (delay: number) => new Promise((res) => setTimeout(res, delay));
    
    type Post = {
      title: string;
    };
    
    function postsByUserIdQueryOption(userId: string) {
      return queryOptions({
        queryKey: ['posts', userId],
        queryFn: () =>
          sleep(2000).then((): Post[] => [{ title: `First post by ${userId}` }]),
      });
    }
    
    const userId = ref('some-user-id');
    
    function useEnabledExample() {
      return useQuery(
        computed(() => ({
          ...postsByUserIdQueryOption(userId.value),
          enabled: false,
          // ^ enabled works without errors, and also autocompletable
        }))
      );
    }
    
    function useBrokenExample() {
      return useQuery(
        computed(() => ({
          ...postsByUserIdQueryOption(userId.value),
          select: (res) => res,
          //       ^ select autocompletable, but results in an error
          // also `res` should be inferrable as Post[], but unfortunately typescript can't infer based on useQuery types, because computed stands in between useQuery and postsByUserIdQueryOption
        }))
      );
    }
    
    function useExplicitTypingExample() {
      return useQuery(
        computed(() => ({
          ...postsByUserIdQueryOption(userId.value),
          select: (res: Post[]) => res,
          //            ^ if we type `res` explicitly everything is fine
        }))
      );
    }
    
    function useNonComputedExample() {
      return useQuery({
        ...postsByUserIdQueryOption('some-user-id'),
        select: (res) => res,
        //      ^ infers fine, because computed wrapper does not get in the way
      });
    }
    
    function useAdditionalQueryOptionsExample() {
      return useQuery(
        computed(() =>
          queryOptions({
            ...postsByUserIdQueryOption(userId.value),
            select: (res) => res,
            //       ^ infers correctly, but useQuery < computed < queryOptions < ... is a lot of boilerplate
          })
        )
      );
    }
    
    export const useExample = useBrokenExample;
    

    This is very wip, has some unsolved typescript errors and probably bugs, but I would imagine solution like this https://github.com/temoncher/tanstack-query/pull/1

    But accepting getter as a parameter instead of whatever it accepts now in various functions will be a huge breaking change for vue-query, not sure if it is really viable.

    edit: added workaround proposed by @bartlangelaan

  14. TkDodocommented

    I'm not aware of a way to add packages into typescript playground

    you can just import stuff in the TS playground, see the other example playgrounds that were posted.

  15. TkDodo added labelspackage: vue-query

  16. TkDodocommented

    okay I’m seeing that @tearaj was mixing issues here :/

    The vue issue seems to be related to computed, I don’t know enough about vue to look into this.

    The second issue is imo just how typescript works, expanding the union. will not look into this further.

  17. I think @tearaj 's problem is not related to this one, but can be opened as a separate one

    Here is minimal reproduction in typescript playground

    import { queryOptions, useQuery } from '@tanstack/react-query';
    
    const optNoQueryOptions = {
      hasName: () => ({
        queryKey: ['A'],
        queryFn: async () => Promise.resolve({ name: 'Jackson' }),
      }),
      hasNameAndId: () =>
        ({
          queryKey: ['B'],
          queryFn: async () => Promise.resolve({ name: 'Jackson', id: '1234' }),
          select: (data: { name: string; id: string }) => ({ name: data.name, id: data.id }),
          //             ^ have to manually type, because lack of queryOptions
        }),
    }
    
    function whatIsTypeOfQueryFn1(type: keyof typeof optNoQueryOptions) {
      const queryInput = optNoQueryOptions[type]();
    
      const res = useQuery(queryInput)
      //                   ^ no error, works fine
    
      return res.data
      //         ^ { name: string } | undefined
    }
    
    const optWithQueryOptions = {
      hasName: () => ({
        queryKey: ['A'],
        queryFn: async () => Promise.resolve({ name: 'Jackson' }),
      }),
      hasNameAndId: () =>
        queryOptions({
          queryKey: ['B'],
          queryFn: async () => Promise.resolve({ name: 'Jackson', id: '1234' }),
          select: (data) => ({ name: data.name, id: data.id }),
          //       ^ don't have to manually type, because queryOptions
        }),
    }
    
    function whatIsTypeOfQueryFn2(type: keyof typeof optWithQueryOptions) {
      const queryInput = optWithQueryOptions[type]();
    
      const res = useQuery(queryInput)
      //                    ^ errors
    
      return res.data
      //         ^ { name: string; id: string } | undefined
    }
    
    // but whatIstypeofQueryFn1 shoudl be identical to whatIsTypeOfQueryFn2, because queryOptions is just an identity function

    I think there is something wrong with queryOptions function types (not really related to react), but error is only easily reproducible with useQuery beside it.

  18. Hey @TkDodo , sorry regarding the mixing issues i thought the type inference bit was the issue mentioned here and it looked pretty similar, let me know if i should create a new issue for this.

    Referring back to this comment the types at compile time is still be computed to be the same in the given example, since if we are to explicitly index the options within useQuery as done in correctlyCompilesAndInfers it works just fine.

    Thanks @temoncher for this, i have slightly changed the example (attached ts playground link below) to show that it still compiles on whatIsTypeOfQueryFn1 when the select option returns { name: string }, and as mentioned, it looks like this type inference issue only occurs when the queryOptions factory function is used to generate the options but not when manually typed and written (as done in optNoQueryOptions and used in whatIsTypeOfQueryFn1)

    Attaching TS playground link -> click here

  19. @xpowerHZ i fixed my issue with .npmrc file containing node-linker=hoisted , try it

  20. @xpowerHZ Should work now with getter instead of computed around query options.

  21. Great! We can now use getters in some simple situations for useQuery.

    But, I have a couple of issues here:

    1. Can we implement similar getter interface for useInfiniteQuery, useQueries and useMutation? I'm kind of puzzled why do we have different apis for these composables, to me it seems unintuitive
    2. There are some issues regarding staleTime and refetchInterval props (maybe there are more, but I ran into these two). For some reason I can't use function-based value for staleTime and refetchInterval with vue-query. @tanstack/query-core's QueryObserver can accept a function in similar way as enabled option can, this way I can configure staleTime and refetchInterval based on query.meta. But in case of useQuery I can pass a function only to enabled prop (and I also need to wrap it, which is weird, but fine), and for staleTime and refetchInterval I only can provide static values. Playground repro

    Let me know in case you want me to open these questions as separate issues

    1. useInfiniteQuery should work as well. It should be quite easy to add it to other composables as well.

    2. There is no problem with staleTime or refetchInterval, just remove the function wrapper.

    enabled is the only prop that initially supported getter for reactivity and we cannot easily remove it now until next major version cause it would be a breaking change.

  22. Thanks We tried it out and were able to remove our wrapper functions around useQuery and useInfiniteQuery. This is still weird that even return value of getters can have MaybeRef's in it, but we just don't use these and it's fine for us

Sign in to join this conversation.