【问题标题】:Forbid any error typescript type in catch禁止 catch 中的任何错误打字稿类型
【发布时间】:2021-03-09 01:08:38
【问题描述】:

有没有办法通过编译器选项/eslint 禁止任何类型的错误或强制注释为 error: unknown

function justDoIt(arg: string){}

// because error is any type this works :(
smth().catch(error => justDoIt(error))

【问题讨论】:

  • 是的,很多很多东西不幸被输入为any而不是unknown

标签: typescript eslint


【解决方案1】:

有一个 eslint 规则可以强制您必须在 promise .catch 处理程序中使用 unknownhttps://github.com/cartant/eslint-plugin-etc/blob/main/docs/rules/no-implicit-any-catch.md

此外,如果您使用的是 typescript 4.0 或更高版本,请在 try/catch 块中使用 now supports 打字稿 unknown。所以结合 async await 你可以做:

try {
  await smth();
} catch (error: unknown) {
  justDoIt(error); // disallowed by the types
}

这可以通过不同的 eslint 规则强制执行:https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md

Eslint 配置规则,第一个是 try/catch,第二个是 promise 链。

"@typescript-eslint/no-implicit-any-catch": ["error", { "allowExplicitAny": true }],
"etc/no-implicit-any-catch": ["error", { "allowExplicitAny": true }]

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2018-11-30
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多