Skip to content
Source
Sign inSign up
TanStack/query

`TData` generic can be inferred or specified incorrectly, causing unexpected runtime errors. #8639

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

Describe the bug

Related to https://github.com/TanStack/query/issues/4770, revitalizing since NoInfer/overloads can at least partially help.

  • TQueryFnData is directly inferred from queryFn specified in the hook options options
  • TData defaults to TQueryFnData, but can be specified via a generic or annotated return type
  • When TData generic is populated (by inference, or explicitly) , nothing enforces that there's type compatibility until you put a select function, leading to uncaught runtime breaks.

Your minimal, reproducible example

https://codesandbox.io/p/devbox/vigilant-forest-7j45zd?file=%2Fsrc%2Findex.tsx%3A58%2C1

Steps to reproduce

See that usePosts and usePosts2 both have a data type claiming to be number, but are instead a Post at runtime.

Examples:

function usePosts() {
  return useQuery<Post[], Error, number, string[]>({
    queryKey: ['posts'],
    queryFn: async (): Promise<Array<Post>> => {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/posts'
      );
      return await response.json();
    },
  });
}

function usePosts2(): UseQueryResult<number, Error> {
  return useQuery({
    queryKey: ['posts'],
    queryFn: async (): Promise<Array<Post>> => {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/posts'
      );
      return await response.json();
    },
  });
}

Expected behavior

I expect to get a type-error, because I haven't specified a select function and TQueryFnData does not equal TData, therefore we have easy, uncaught runtime breaks.

Potential solutions:

  • Using NoInfer on the UseQueryResult<NoInfer<TData>, TError>, will at least prevent usePost2 issue
  • We should be able to write a conditional type by using additional overloads (untested/hypothetically) to narrow on the condition where we have a select specified.
type UseQueryOptionsWithSelect = ...
type UseQueryOptionsWithoutSelect = ...

declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UseQueryOptionsWithoutSelect<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TQueryFnData extends TData ? NoInfer<TData> : never, TError>;
declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UseQueryOptionsWithSelect<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<NoInfer<TData>, TError>;

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

N/A

Tanstack Query adapter

None

TanStack Query version

5.66.0

TypeScript version

5.7.2

Additional context

No response

  1. Using NoInfer on the UseQueryResult<NoInfer, TError>, will at least prevent usePost2 issue

    If that fixes it, please open a PR with that fix, including the appropriate type tests.

    We should be able to write a conditional type by using additional overloads

    We don’t want more overloads. If you add angle brackets <> to useQuery, you are basically doing a type assertion. I don’t want to add more complexity for that, as it’s not a recommended thing to do, as documented here: https://tanstack.com/query/v5/docs/framework/react/typescript

  2. TkDodo added labelstypes

  3. Started draft PR here https://github.com/TanStack/query/pull/8654 -- just indexed on useQuery to get first thoughts/before digging into how to more generally apply NoInfer to query-core types.

  4. birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-query

  5. I understood the point to be that mismatches between TData and TQueryFnData don't raise a type error.

    However, when I actually run the above code in the code sandbox, I get a type mismatch error in the return part, and when I run the build, I get an error and it doesn't build. Please let me know if there's something I'm missing.

    Image

  6. @novice0840 What you are seeing is the error from usePosts2, not from usePosts.

    In usePosts2, the return type is explicitly declared as UseQueryResult<number, Error>. Because of that, TypeScript enforces that TData must be number, while the queryFn actually returns Post[]. This causes a type mismatch and correctly produces a compile-time error.

    However, in usePosts, all generics are explicitly provided to useQuery:

    useQuery<Post[], Error, number, string[]>

    Here, TypeScript assumes that TData (number) is intentionally specified by the developer. Since no select function is provided, this creates a mismatch between TQueryFnData (Post[]) and TData (number), but TypeScript does not report an error.

    So the behavior described in the issue refers specifically to the usePosts case, where the mismatch is not caught by the type system.

  7. We've identified a potential issue with the NoInfer statement that appears to be causing type spreads to default to Any in our TanStack integration. Following some recent return type adjustments, TypeScript wasn't flagging this as expected, so we're now working through a fairly large codebase to locate and address the root cause. Unfortunately, I cannot share additional context on this one given that it's a production implementation, but we're actively investigating the typing behavior.

    Context: Usage of a wrapper that receives the query UseQueryResult now doesn't infer the types leading to "ANY" as fallback thus making all data without type

    interface Props<T> {
      query: UseQueryResult<T>;
      emptyFallback?: ReactNode | (() => ReactNode);
      children: (data: T) => ReactNode;
    }
    
    <UIWrapperDataQuery query={parameter}>
      {(data "marked as any") => (
        children
      )}
    </UIWrapperDataQuery>
    Image Image Image
  8. Hi! Following up on this — since the NoInfer approach was greenlit above and useQuery's return types already have NoInfer on main, I'd like to pick up the remaining part: extending it to useInfiniteQuery, useSuspenseQuery, and useSuspenseInfiniteQuery return types, with type tests.

    I'm aware of the narrowing regression reported in #11018 (and the open fix in #11022), so I'll include discriminated-union narrowing cases in the type tests to make sure the infinite/suspense hooks don't make that situation worse.

    Planning to open a PR shortly!

  9. I think if you annotate useQuery<A,B,C,D> you’re basically doing a type assertion, which isn’t something you should be doing in the first place. Imo this is a non-issue.

  10. TkDodo closed this

  11. TkDodo added labelswontfix

Sign in to join this conversation.