Skip to content

Build error: TS2345: Argument of type 'ApiResult<any>' is not assignable to parameter of type 'T | PromiseLike<T>'. #95

Closed
@lavocatt

Description

@lavocatt

Describe the bug
There's an issue building the generated code.

To Reproduce
npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./api-server/config/openapi.yml -c axios -o src/openapi/jolokia

Upon building:

ERROR in /home/tlavocat/dev/activemq-artemis-self-provisioning-plugin/src/openapi/jolokia/requests/core/request.ts
./openapi/jolokia/requests/core/request.ts 332:12-18
[tsl] ERROR in /home/tlavocat/dev/activemq-artemis-self-provisioning-plugin/src/openapi/jolokia/requests/core/request.ts(332,13)
      TS2345: Argument of type 'ApiResult<any>' is not assignable to parameter of type 'T | PromiseLike<T>'.
  Type 'ApiResult<any>' is not assignable to type 'T'.
    'T' could be instantiated with an arbitrary type which could be unrelated to 'ApiResult<any>'.
ts-loader-default_ca3771bf23e1d373
 @ ./openapi/jolokia/requests/services.gen.ts 3:0-54 21:15-24 49:15-24 97:15-24 137:15-24 191:15-24 227:15-24 254:15-24 282:15-24 339:15-24 389:15-24 417:15-24 463:15-24 520:15-24
 @ ./openapi/jolokia/requests/index.ts 6:0-31 6:0-31
 @ ./utils/api-server.tsx 7:0-62 46:19-40
 @ ./utils/index.ts 7:0-29 7:0-29
 @ ./brokers/broker-details/BrokerDetails.container.tsx 8:0-94 27:24-38 41:32-47 56:17-37 56:1559-1575
 @ ./brokers/broker-details/index.ts 1:0-52 1:0-52
 @ container entry BrokerDetailsPage[0]

OpenAPI spec file

https://github.com/artemiscloud/activemq-artemis-self-provisioning-plugin/blob/main/api-server/config/openapi.yml

tsconfig

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "outDir": "./dist",
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es2020",
    "jsx": "react-jsx",
    "strict": false,
    "esModuleInterop": true,
    "noUnusedLocals": true,
    "resolveJsonModule": true,
    "forceConsistentCasingInFileNames": true,
    "importHelpers": true,
    "declaration": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "skipLibCheck": true,
    "paths": {
      "@app/*": ["src/*"],
      "react": ["./node_modules/@types/react"]
    }
  },
  "include": ["./src/*", "./src/**/*", "setupTests.ts", "__mocks__"],
  "exclude": ["node_modules", "dist"]
}

eslint config

env:
  browser: true
  es2021: true
  node: true
  es6: true
extends:
  - eslint:recommended
  - plugin:react/recommended
  - plugin:@typescript-eslint/recommended
  - prettier
parser: '@typescript-eslint/parser'
parserOptions:
  ecmaFeatures:
    jsx: true
  ecmaVersion: 2016
  sourceType: module
plugins:
  - prettier
  - react
  - '@typescript-eslint'
rules:
  prettier/prettier:
    - error
  react/react-in-jsx-scope: 'off'
  react/no-unescaped-entities: 'off'
  react/prop-types: 'off'
settings:
  react:
    version: detect

Expected behavior
no compilation error

  • OS: fedora
  • Version: @tanstack/react-query": "^5.32.0", "axios": "^1.6.8",

Activity

seriouslag

seriouslag commented on Apr 26, 2024

@seriouslag
Collaborator

Is this a new issue, did this work in previous versions?

seriouslag

seriouslag commented on Apr 26, 2024

@seriouslag
Collaborator

I replicated the issue, and it seems to be an issue when using Axios and the base-generated (non-provided) request file from the underlying service generator @hey-api/openapi-ts

We need to create a ticket and reproducible example with @hey-api/openapi-ts.

2 workarounds I can think of:

  • switch to fetch instead of Axios
    • npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./api-server/config/openapi.yml -c fetch -o src/openapi/jolokia
  • pass in a working request file
    • npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./api-server/config/openapi.yml -c axios -o src/openapi/jolokia --request ./request.ts
      • add a request.ts file to the root of your repo.
// request.ts file
/* eslint-disable */
// @ts-nocheck

import axios from "axios";
import type { RawAxiosRequestHeaders } from "axios";

import type { ApiRequestOptions } from "./ApiRequestOptions";
import { CancelablePromise } from "./CancelablePromise";
import type { OpenAPIConfig } from "./OpenAPI";

// Optional: Get and link the cancelation token, so the request can be aborted.
const source = axios.CancelToken.source();

const axiosInstance = axios.create({
  // Your custom Axios instance config
  baseURL: "http://localhost:4010",
  headers: {
    // Your custom headers
  } satisfies RawAxiosRequestHeaders,
});

// Add a request interceptor
axiosInstance.interceptors.request.use(
    function (config) {
        // Do something before request is sent
        if (!config.url || !config.params) {
            return config;
        }

        Object.entries<any>(config.params).forEach(([key, value]) => {
            const stringToSearch = `{${key}}`;
            if(config.url !== undefined && config.url.search(stringToSearch) !== -1) {
                config.url = config.url.replace(`{${key}}`, encodeURIComponent(value));
                delete config.params[key];
            }
        });

        return  config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
axiosInstance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

export const request = <T>(
  config: OpenAPIConfig,
  options: ApiRequestOptions
): CancelablePromise<T> => {
  return new CancelablePromise((resolve, reject, onCancel) => {
    onCancel(() => source.cancel("The user aborted a request."));

    let formattedHeaders = options.headers as RawAxiosRequestHeaders;
    if (options.mediaType) {
      formattedHeaders = {
        ...options.headers,
        "Content-Type": options.mediaType,
      } satisfies RawAxiosRequestHeaders;
    }

    return axiosInstance
      .request({
        url: options.url,
        data: options.body,
        method: options.method,
        params: options.path,
        headers: formattedHeaders,
        cancelToken: source.token,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};
lavocatt

lavocatt commented on Apr 29, 2024

@lavocatt
Author

Is this a new issue, did this work in previous versions?

I don't know, it's my first time using the project.

switch to fetch instead of Axios

  • npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./api-server/config/openapi.yml -c fetch -o src/openapi/jolokia

This leads to the same issue:

ERROR in /home/tlavocat/dev/activemq-artemis-self-provisioning-plugin/src/openapi/jolokia/requests/core/request.ts
./openapi/jolokia/requests/core/request.ts 335:12-18
[tsl] ERROR in /home/tlavocat/dev/activemq-artemis-self-provisioning-plugin/src/openapi/jolokia/requests/core/request.ts(335,13)
      TS2345: Argument of type 'ApiResult<any>' is not assignable to parameter of type 'T | PromiseLike<T>'.
  Type 'ApiResult<any>' is not assignable to type 'T'.
    'T' could be instantiated with an arbitrary type which could be unrelated to 'ApiResult<any>'.
ts-loader-default_ca3771bf23e1d373
 @ ./openapi/jolokia/requests/services.gen.ts 3:0-54 21:15-24 49:15-24 97:15-24 137:15-24 191:15-24 227:15-24 254:15-24 282:15-24 339:15-24 389:15-24 417:15-24 463:15-24 520:15-24
 @ ./openapi/jolokia/requests/index.ts 6:0-31 6:0-31
 @ ./utils/api-server.tsx 7:0-62 39:19-40
 @ ./utils/index.ts 7:0-29 7:0-29
 @ ./brokers/broker-details/BrokerDetails.container.tsx
 @ ./brokers/broker-details/index.ts 1:0-52 1:0-52
 @ container entry
pradel

pradel commented on Apr 29, 2024

@pradel

I am also getting this error with fetch, seems that the type error is actually correct and the generated request.ts file should be resolve(result.body); instead of resolve(result);

seriouslag

seriouslag commented on Apr 30, 2024

@seriouslag
Collaborator

The underlying service generator changed its defaults.

We now need to pass a setting to generate the same response.

Providing the serviceResponse argument with the value of body will fix the types.

I opened a PR to set the default value to body, #98

@lavocatt and @pradel, thank you for opening the issue and helping debug.

use the following in the meantime until the new version of this library is released.

npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./api-server/config/openapi.yml -c axios -o src/openapi/jolokia --serviceResponse body
seriouslag

seriouslag commented on May 1, 2024

@seriouslag
Collaborator

New version is released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @pradel@seriouslag@lavocatt

      Issue actions

        Build error: TS2345: Argument of type 'ApiResult<any>' is not assignable to parameter of type 'T | PromiseLike<T>'. · Issue #95 · 7nohe/openapi-react-query-codegen