TanStack / query

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
https://tanstack.com/query
MIT License
41.96k stars 2.85k forks source link

useQuery() hook vulnerable to type errors #7530

Open JK-WP opened 3 months ago

JK-WP commented 3 months ago

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) });
}
TkDodo commented 3 months ago

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.