Alexei Delezhov
Alexei Delezhov

Reputation: 1573

Which type for Error in Axios in TypeScript

I have the following working code:

                try {
                    self.loadingFrameMarkup = true;
                    const { data }: AxiosResponse<IMarkupFrameData> = yield axios.post<IMarkupFrameData>(
                        Endpoints.LoadMarkupFrame,
                        {
                            studyID: self.studyID,
                            frameIndex: frameIndex,
                        }
                    );

                    result = {
                        ...data,
                        layers: data.layers.filter((it) => it),
                    };
                    self.loadingFrameMarkup = false;
                } catch (error: AxiosError | Error) {
                    if (error?.response?.status === 401) {
                        self.state = QueueState.Unauthorized;
                    } else {
                        self.state = QueueState.Failure;
                    }
                }

typescript-eslint show error Catch clause variable type annotation must be 'any' or 'unknown' if specified.ts(1196) (alias) interface AxiosError<T = unknown, D = any>

What type should the error be in Axios?

Upvotes: 1

Views: 3973

Answers (3)

NeERAJ TK
NeERAJ TK

Reputation: 2695

You can't directly give type definition of error in the catch block. You can read more about this here. Best solution would be giving type inside the catch block, as :

catch (err) {
       if ((error as AxiosError)?.response?.status === 401) {
             self.state = QueueState.Unauthorized;
           } else {
              self.state = QueueState.Failure;
         }
     }

Upvotes: 2

Obaida Alhassan
Obaida Alhassan

Reputation: 601

The types in TypeScript only exist until the code is compiled. Once it's compiled, all you've got is typeless JavaScript.

Having type filters on catch clauses would require checking the errors' types at runtime, and there's simply no reliable way to do that, so simply assign it to any or unknown and then cast the error if applicable

catch (error: Error| any){
/// code
}

Upvotes: 1

sb raad
sb raad

Reputation: 115

You can do something similar to

    try {
        ...
        ...
        ...
    } catch (err) {
      console.log(err as AxiosError)
      // or
      // const error = err as AxiosError
    }

Upvotes: 1

Related Questions