Skip to content

useQuery() hook vulnerable to type errors #7530

Open
@JK-WP

Description

@JK-WP

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) });
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions