axios-mock-adapter icon indicating copy to clipboard operation
axios-mock-adapter copied to clipboard

Not assignable to type MockArrayResponse

Open matttk opened this issue 1 year ago • 2 comments

I updated to v2.1.0 today and now I am getting multiple compile errors with "not assignable to type MockArrayResponse". I see from the releases page that MockResponse types have been added.

The problem is that I have some helper functions that return some responses.

e.g.

function getResponse(config: AxiosRequestConfig) {
  // blah blah
  
  return [
    200,
    {
      // etc.
    }
  ];
}

If I simply add : [number, { [key: string]: unknown }] as a return type for the above function, the compile error goes away. Without it, typescript automatically assumes the type is Array<number | { /* object description here */ }>, which is not accepted.

If I just copy and paste MockArrayResponse into the file, everything compiles just fine. Is there any reason not to export this type?

matttk avatar Nov 08 '24 13:11 matttk

Hmmm... I fixed the version to 2.0.0 and still have the issue, but I was also updating TypeScript to 5.6.3. When I revert that back to 5.6.2, it works fine, so I'm assuming the problem is actually due to some TS changes.

Nevertheless, having an response type would help here.

matttk avatar Nov 08 '24 15:11 matttk

I met same isseue.

So I declared CallbackResponseSpecFunc's return type. Like below.

/* eslint-disable @typescript-eslint/no-explicit-any */

import { AxiosRequestConfig } from 'axios';
import MockAdapter from 'axios-mock-adapter';

declare module 'axios-mock-adapter' {
  interface AxiosHeaders {
    [key: string]: string | number | boolean | null | undefined;
  }

  type MockArrayResponse = [status: number, data?: any, headers?: AxiosHeaders];

  type MockObjectResponse = {
    status: number;
    data: any;
    headers?: AxiosHeaders;
    config?: AxiosRequestConfig;
  };

  type MockResponse = MockArrayResponse | MockObjectResponse;

  type CallbackResponseSpecFunc = (
    config: AxiosRequestConfig,
  // add any[] and Promise<any[]>
  ) => MockResponse | Promise<MockResponse> | any[] | Promise<any[]>; 

  type ResponseSpecFunc = <T = any>(
    statusOrCallback: number | CallbackResponseSpecFunc,
    data?: T,
    headers?: AxiosHeaders,
  ) => MockAdapter;
}

tolluset avatar Apr 09 '25 22:04 tolluset