Skip to content

TData gets incorrectly inferred in useQuery when providing both select and onSuccess #3193

@davbrito

Description

@davbrito

Describe the bug

Say that I have a queryFn that returns type T and a select function that returns type U. If I provide a onSuccess function, TypeScript complains that select function should return type T. And the onSuccess function data parameter gets typed as T.

declare const data: T;

const query = useQuery(
  ['queryKey'],
  () => data,
  {
     select: data => data.u // Returns type "U" but TypeScript wants "T" for some reason
     onSuccess(data) { // Should be type U but is inferred as T
        console.log(data)
     }
  })

The workaround is to explicitly type the onSuccess param to be of type U.

declare const data: T;

const query = useQuery(
  ['queryKey'],
  () => data,
  {
     select: data => data.u // Works as expected
     onSuccess(data: U) {
        console.log(data)
     }
  })

Your minimal, reproducible example

https://codesandbox.io/s/serene-hofstadter-56r0r

Steps to reproduce

  1. Create a query with useQuery.
  2. Pass a select function that select some data with diferent type than returned by the queryFn.
  3. Pass a onSuccess function and let TypeScript infer the parameter types.

Expected behavior

  • The first parameter of the onSuccess should be the same as the return type of the select function.
  • The TData type should be inferred with the return type of the select function.

How often does this bug happen?

Every time

Screenshots or Videos

image
image

Platform

  • OS: Windows 11
  • Browser: Not related because it's a TypeScript issue.

react-query version

v3.34.8

TypeScript version

v4.5.4

Additional context

No response

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