Skip to content

Types no longer inferred correctly #2753

@jamesots-tq

Description

@jamesots-tq

In version 3.24.0 and earlier, I can call useQuery like this, without needing to specify the generic types:

export function useGetThing(
  id: string | undefined,
  options?: UseQueryOptions<Thing | undefined>
): QueryObserverResult<Thing | undefined> {
  return useQuery(
    ['key', text],
    () => (id === undefined ? undefined : api.getThing(id)),
    options
  );
}

I often do this so that I can have a call to useGetThing(id, {enabled: Boolean(id)}), and have it only call the api when the id is not undefined - usually as it's the result of a previous query. I can't call api.getThing with an undefined id, so I have the check in the query function and have it return undefined when the query is not enabled. (Of course, this doesn't get called when the query is disabled, but it keeps TypeScript happy).

However, since 3.24.1, I have to include the type in the useQuery call: useQuery<Thing | undefined>(...), otherwise it complains that 'Thing | undefined is not assignable to Thing'.

(I imagine there may be better ways to write my useGetThing function, but nevertheless, this still appears to be a regression).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions