Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Didn't take Generics in isAxiosError() for AxiosError<any> #3815

Closed
latipun7 opened this issue May 27, 2021 · 4 comments
Closed

Didn't take Generics in isAxiosError() for AxiosError<any> #3815

latipun7 opened this issue May 27, 2021 · 4 comments

Comments

@latipun7
Copy link

latipun7 commented May 27, 2021

Describe the issue

axios.isAxiosError is type predicated isAxiosError(payload: any): payload is AxiosError; in node_modules/axios/index.d.ts while AxiosError take generics default to any.

How can I make isAxiosError is predicated to payload is AxiosError<Response>?

Example Code

Code snippet to illustrate your question

interface Response {
  error: boolean;
  message: string;
  count?: number;
  hotels?: Hotel[];
}

// ...
catch (error: unknown) {
  if (axios.isAxiosError(error)) {
    if (error.response) {
      return error.response.data.message; // error now is AxiosError<any>, so the data is `any` which I don't want
    }
  }
}

Expected behavior, if applicable

I can type AxiosError with AxiosError<Response> generics with isAxiosError accept generics.

// ...
catch (error: unknown) {
  if (axios.isAxiosError<Response>(error)) {
    if (error.response) {
      return error.response.data.message; // now this is return `string` from the Response interface
    }
  }
}

Environment

  • Axios Version [0.21.1]
  • Adapter [XHR/HTTP]
  • Browser [Microsoft Edge]
  • Browser Version [90.0.818.66]
  • Node.js Version [14.17.0]
  • OS: [WSL]
  • Additional Library Versions [Typescript 4.2.4]

Additional context/Screenshots

@Guuz
Copy link

Guuz commented Oct 1, 2021

Any updates on this?

@latipun7 latipun7 changed the title isAxiosError() didn't take Generics for AxiosError<any> Didn't take Generics in isAxiosError() for AxiosError<any> Oct 1, 2021
@tfoxy
Copy link

tfoxy commented Oct 25, 2021

Quick fix until #3816 is merged is to create the following file

// axios.d.ts

declare module "axios" {
  interface AxiosStatic {
    isAxiosError<T = any>(payload: any): payload is AxiosError<T>;
  }
}

export {};

@Argeento
Copy link
Contributor

Clear PR #4344

AxiosError<T = any, D = any> - now T and D type variables are supported in isAxiosError method

@Webbrother
Copy link

Workaround for 0.x version:

if (axios.isAxiosError(error)) {
   (error as AxiosError<MyErrorInterface>).response?.data.message // string | undefined
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants