Skip to content

useQuery select callback parameter is inferred as unknown instead of endpoint response type #2852

Description

@Mohamed-maher50

openapi-react-query version

0.5.4

Description

useQuery does not correctly infer the OpenAPI response type for the select callback.

The endpoint response type is available from the generated OpenAPI paths type, but inside select, the callback parameter is inferred as unknown. Because of this, mapper functions have to accept unknown and manually cast/narrow the response.

Package versions:

  • openapi-react-query: 0.5.4
  • openapi-fetch: 0.17.0
  • @tanstack/react-query: 5.100.9
  • typescript: 5.x

Example actual behavior:

function mapAdminRolesListResponse(response: unknown): DashboardRolesListResponse {
  // Required workaround because select does not infer the real endpoint response type.
}

Example error shape:
Type '(response: RolesResponse) => DashboardRolesListResponse' is not assignable to type '(data: unknown) => DashboardRolesListResponse'.
Type 'unknown' is not assignable to type 'RolesResponse'.

### Reproduction


**Reproduction**
```md
```ts
import { keepPreviousData } from "@tanstack/react-query";
import createFetchClient from "openapi-fetch";
import createClient from "openapi-react-query";

import type { paths } from "./openapi";

const fetchClient = createFetchClient<paths>({
  baseUrl: "",
});

const $api = createClient(fetchClient);

type RolesResponse =
  paths["/admin/roles"]["get"]["responses"][200]["content"]["application/json"];

type DashboardRolesListResponse = {
  items: unknown[];
};

function mapAdminRolesListResponse(
  response: RolesResponse
): DashboardRolesListResponse {
  return {
    items: response.data.data,
  };
}

function useRolesQuery() {
  return $api.useQuery(
    "get",
    "/admin/roles",
    {
      params: {
        header: {
          Accept: "application/json",
        },
      },
    },
    {
      placeholderData: keepPreviousData,
      select: mapAdminRolesListResponse,
    }
  );
}

### Expected result


**Expected result**
```md
The `select` callback should infer the response data type for the selected method/path.

For this call:

```ts
$api.useQuery("get", "/admin/roles", init, {
  select: mapAdminRolesListResponse,
});

### Extra

- [ ] I’m willing to open a PR (see [CONTRIBUTING.md](https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-react-query/CONTRIBUTING.md))

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingopenapi-react-queryRelevant to openapi-react-query

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions