skip to Main Content
const apiCallingFunction = async (data: any) => {
  try {
    let response = await axiosPost("/api", { ...data });
    return response;
  } catch (err: any) {
    return err.response;
  }
};

I want to remove any from the catch block.

2

Answers


  1. import { AxiosError } from "axios";
    
    const apiCallingFunction = async (data: any) => {
      try {
      let response = await axiosPost("/api", { ...data });
      return response;
      } catch (err: unknown) {
       return (err as AxiosError).response;
      }
     };
    

    Axios Has Inbuilt Type for error Known As AxiosError

    Login or Signup to reply.
  2. I don’t think that "remove any from catch block" is a good practice for this problem, since anything that goes into catch block should be unexpected error, which should be typed as unknown. For reference, this practice has been discussed here, in the official github of Typescript.

    I would recommend you to just leave the catch block catch(err) { // some code } without adding type to it if you are using Typescript >4.4 (explain in this PR)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search