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?
CodePudding user response:
You can do something similar to
try {
...
...
...
} catch (err) {
console.log(err as AxiosError)
// or
// const error = err as AxiosError
}
CodePudding user response:
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
}
CodePudding user response:
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;
}
}