Home > other >  How type error property in catch block typescript?
How type error property in catch block typescript?

Time:10-15

I have next code:

import axios, {AxiosError} from "axios";

try {
  some request
} catch(err:AxiosError) {
 console.log(error.response) //doesnt work
 console.log(error.response?.data?.message) //doesnt work
 if(error.response?.data?.statusCode === 401) {
   logout()
 }
}

I cannot check status code inside bacause of typescript how to describe the error type correctly without resorting to the any type? I couldn't find how people handle this error in typescript, maybe I'm missing something

CodePudding user response:

Typescript has no way to verify which types of values might be thrown by arbitrary code. So up until recently, the error had to be of type any.

} catch (err: any) {

From version 4.0 onward, typescript also allows unknown.

} catch (err: unknown) {

Anything else is not supported. If you want something more specific, you will either need to write code to narrow down what type of thing was thrown, or you will need to use a type assertion. Keep in mind that a type assertion is a way to tell typescript "i know more than you do, so don't check my work". If you assert that it's an AxiosError, but it could actually be something else, typescript cannot point out that mistake to you.

catch (err: unknown) {
   const error = err as AxiosError;
   //...
}
  • Related