禁止 catch 中的任何错误打字稿类型

时间:2021-03-08 16:13:22

标签: typescript eslint

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

function justDoIt(arg: string){}

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

1 个答案:

答案 0 :(得分:3)

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

此外,如果您使用的是 typescript 4.0 或更高版本,请在 try/catch 块中使用 unknown 打字稿 now supports。所以结合 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 }]