Skip to content
Source
Sign inSign up
TanStack/query

useQuery() hook vulnerable to type errors #7530

Send to my agent
ClosedJK-WP(GitHub profile, opens in a new tab) opened this issue 2 comments

Describe the bug

There is a problem with hidden typescript type errors in the useQuery() hook when select is not defined.

Your minimal, reproducible example

Simple 1-line example provided inline

Steps to reproduce

Try compiling the following:

  const queryResult: UseQueryResult<number> = useQuery({
    queryKey: ['key'],
    queryFn: async () => 'not a number',
  });

Expected behavior

This should produce a type error, since queryResult.data will contain a string, contrary to the declared type of number.

But it compiles cleanly with no type errors detected.

A type error will, however, be detected if a no-op selectFn is provided:

  const queryResult: UseQueryResult<number> = useQuery({
    queryKey: ['key'],
    queryFn: async () => 'not a number',
    select: (s) => s,
  });

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

N/A

Tanstack Query adapter

react-query

TanStack Query version

v5.40.1

TypeScript version

v5.2.2

Additional context

One possible avenue of attack might be to switch the template arguments to take the type of the select function instead, and try to infer TData from that. For example (where I've simplified to focus just on the types of interest):

interface MyQueryOptions<TQueryFnData = unknown, TSelect = unknown> {
  queryFn: () => Promise<TQueryFnData>;
  selectFn?: TSelect;
}

interface MyUseQueryResult<TData = unknown> {
  data: TData;
}

declare function useMyQuery<TQueryFnData = unknown, TSelect = unknown>(
  options: MyQueryOptions<TQueryFnData, TSelect>,
): MyUseQueryResult<TSelect extends (data: TQueryFnData) => infer TData ? TData : TQueryFnData>;

function thisHasATypeError(): MyUseQueryResult<number> {
  return useMyQuery({ queryFn: async () => 'not a number' });
}

function thisIsTypeCorrect(): MyUseQueryResult<number> {
  return useMyQuery({ queryFn: async () => 'not a number', selectFn: (s) => Number.parseInt(s) });
}
  1. if you know a good way to fix this, please make a PR including type tests. My general recommendation is to use type inference and not slap the UseQueryResult type on your custom hooks. It will also take away some optimizations we do with overloads.

  2. TkDodo added labelshelp wanted

  3. TkDodo added labelstypes

  4. @TkDodo I made PR to solve this issue. Can you give me a feedback on this PR? #8683

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

  6. TkDodo closed this

Sign in to join this conversation.