简体   繁体   English

如何在 TypeScript 的 catch 块中键入错误属性?

[英]How do you type an error property in a catch block in TypeScript?

I have this code:我有这段代码:

import axios, {AxiosError} from "axios";

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

I can't check the status code inside because of TypeScript. How do I describe the error type correctly without resorting to the any type?由于TypeScript,我无法检查内部状态码。如何在不使用any类型的情况下正确描述错误类型? I couldn't find how people handle this error in TypeScript, maybe I'm missing something.我在 TypeScript 找不到人们如何处理这个错误,也许我遗漏了什么。

Typescript has no way to verify which types of values might be thrown by arbitrary code. Typescript 无法验证任意代码可能抛出哪些类型的值。 So up until recently, the error had to be of type any .所以直到最近,错误必须是any类型。

} catch (err: any) {

From version 4.0 onward, typescript also allows unknown .从 4.0 版开始,打字稿还允许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.如果你断言它是一个 AxiosError,但它实际上可能是别的东西,打字稿不能向你指出那个错误。

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

Alternatively, rather than use a regular catch block, restructure the code to use the Promise.catch(error) method.或者,不要使用常规的catch块,而是重构代码以使用Promise.catch(error)方法。 You can then quote the type of the parameter as (error: AxiosError) or just leave TypeScript to infer the type.然后,您可以将参数的类型引用为(error: AxiosError) ,或者只留下 TypeScript 来推断类型。

eg, assuming "some request" is a GET request, it might look like this:例如,假设“一些请求”是一个 GET 请求,它可能看起来像这样:

import axios from 'axios';

await (async () => {
  axios
    .get('some-url')
    .then((response) => {
      // Some handler logic
    })
    .catch((error) => {
      console.log(error.response); // now works
      console.log(error.response?.data?.message); // now works
      if (error.response?.data?.statusCode === 401) {
        logout()
      }
    });
})();

I encountered this as well, you can do it and @David-Easley hints at but does not provide the syntax.我也遇到过这个,你可以做到,@David-Easley 提示但不提供语法。

If you surround the error variable with brackets, you can then set the type.如果用方括号括起错误变量,则可以设置类型。

Change it from;改变它;

  .catch(error => {

to;到;

  .catch((error:AxiosError) => {

That gives intellisense on the error object.这给出了错误 object 的智能感知。

Just make be sure that you'll always get that error type passed.只需确保您将始终获得该错误类型即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 TypeScript 访问 React State 属性? 类型错误时获取属性不存在 - How do I access React State properties using TypeScript? Get property does not exist on type error 你如何在 React Native 中为 useRef 钩子设置 Typescript 类型? - How do you set the Typescript type for useRef hook in React Native? TypeScript:如何解决 arrays 的“类型不存在属性”错误? - TypeScript: How to solve 'property does not exist for type' error for arrays? 如何解决Typescript中“ object”类型上不存在的“属性”字符串问题 - How To fix 'Property “string” does not exist on type “object”' error in Typescript try catch 块 axios 响应类型为 Blob 没有错误消息 - No error message on try catch block axios Response type is Blob Typescript 错误:类型中缺少属性“类” - Typescript error: Property 'classes' is missing in type ReactJS 中的 Typescript 错误 - 类型上不存在属性 - Typescript error in ReactJS - Property does not exist on type 打字稿类型错误属性不存在 - Typescript type error property does not exist 打字稿错误说类型上不存在属性 - Typescript error says property does not exist on type 如何使用 Redux 工具包(使用 TypeScript)解决“AsyncThunkAction”类型中缺少“属性”类型? - How do I resolve 'Property 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM