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

RTW*_*RTW 2 typescript eslint

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

function justDoIt(arg: string){}

// because error is any type this works :(
smth().catch(error => justDoIt(error))
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 8

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

此外,如果您使用的是 Typescript 4.0 或更高版本,TypeScript现在支持unknown在 try/catch 块中使用。因此,结合 async wait 你可以这样做:

try {
  await smth();
} catch (error: unknown) {
  justDoIt(error); // disallowed by the types
}
Run Code Online (Sandbox Code Playgroud)

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

Eslint 配置规则,第一个用于 try/catch,第二个用于承诺链。

"@typescript-eslint/no-implicit-any-catch": ["error", { "allowExplicitAny": true }],
"etc/no-implicit-any-catch": ["error", { "allowExplicitAny": true }]
Run Code Online (Sandbox Code Playgroud)