简体   繁体   English

如何处理 catch(err) 块上的 @typescript-eslint/no-unsafe-member-access 规则?

[英]How to handle the @typescript-eslint/no-unsafe-member-access rule on catch(err) blocks?

I've recently added eslint to my Typescript codebase.我最近将eslint添加到我的 Typescript 代码库中。

By default, it enables the @typescript-eslint/no-unsafe-member-access .默认情况下,它启用@typescript-eslint/no-unsafe-member-access

And all of sudden, I'm getting tons of lint errors on my catch blocks.突然之间,我的 catch 块上出现了大量 lint 错误。

在此处输入图像描述

Is there a good workaround for this?有没有好的解决方法?

Typescript does not allow me to type it as Error directly from the catch statement like catch(err: Error) . Typescript 不允许我直接从catch(err: Error)之类的 catch 语句中将其键入为Error

I don't want to disable the rule completely, neither I want to add eslint-disable on every catch(err) block.我不想完全禁用规则,也不想在每个catch(err)块上添加eslint-disable

There are various uncertainties in the try block, and JavaScript can throw not just an Error object, but even a string , or even null or undefined . try块中存在各种不确定性,JavaScript 不仅会抛出 Error object,甚至会抛出string ,甚至nullundefined We can use instanceof-narrowing to avoid such a warning我们可以使用instanceof-narrowing来避免这样的警告

try {
  ...
} catch(e) {
  if (e instanceof Error /*CustomError*/) {
   console.log(e.message)
  }
}

This is terribly ugly code, but...这是非常丑陋的代码,但是......

// before
try {
  /*...*/ 
} catch (err) {
  if (err.name == 'AbortError') {
    /*...*/
  }
}

// after
try {
  /*...*/
} catch (err) {
  if ((err as {name?: string})?.name == 'AbortError') {
    /*...*/
  }
}

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

相关问题 @typescript-eslint/no-unsafe-assignment:任何值的不安全赋值 - @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any value @typescript-eslint/no-unsafe-* 规则的新 eslint 错误 - New eslint errors with the @typescript-eslint/no-unsafe-* rules Typescript:ESLint:任何类型值的不安全返回 @typescript-eslint/no-unsafe-return - Typescript : ESLint : Unsafe return of an any typed value @typescript-eslint/no-unsafe-return 如何解决“未找到规则‘@typescript-eslint/rule-name’的定义” - How to resolve "Definition for rule '@typescript-eslint/rule-name' was not found" 加载规则“@typescript-eslint/dot-notation”时出错 - Error while loading rule '@typescript-eslint/dot-notation' eslint 缩进和@typescript-eslint/indent 冲突 - eslint indent and @typescript-eslint/indent conflict 在 Storybook js 中找不到规则“@typescript-eslint/no-implicit-any”的定义 - Definition for rule '@typescript-eslint/no-implicit-any' was not found with Storybook js 任何值上的 eslint 错误不安全成员访问 ['content-type'] - eslint error Unsafe member access ['content-type'] on an any value 如何在 VSCode 中的同一项目中的 .ts 文件和 .js 文件上运行 typescript-eslint - How to run typescript-eslint on .ts files and eslint on .js files in the same project in VSCode ESLint 无法识别“@typescript-eslint/eslint-plugin” - ESLint is not recognizing "@typescript-eslint/eslint-plugin"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM