[英]Forbid any error typescript type in catch
Is there a way to forbid error being of type any or force annotate is as error: unknown
by compiler oprtions/eslint?有没有办法禁止任何类型的错误或强制注释为
error: unknown
编译器选项/eslint 未知?
function justDoIt(arg: string){}
// because error is any type this works :(
smth().catch(error => justDoIt(error))
There's an eslint rule which can enforce that you must use unknown
in promise .catch
handlers: https://github.com/cartant/eslint-plugin-etc/blob/main/docs/rules/no-implicit-any-catch.md有一个 eslint 规则可以强制您必须在 promise
.catch
处理程序中使用unknown
: https://github.com/cartant/eslint-plugin-etc/blob/main/docs/rules/no-implicit-any-catch。 MD
Additionally, if you're using typescript 4.0 or later, typescript now supports using unknown
in try/catch blocks.此外,如果您使用 typescript 4.0 或更高版本,typescript 现在支持在 try/catch 块中使用
unknown
。 So combined with async await you can do:所以结合 async await 你可以做:
try {
await smth();
} catch (error: unknown) {
justDoIt(error); // disallowed by the types
}
And this can be enforced with a different eslint rule: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md这可以通过不同的 eslint 规则强制执行: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md
Eslint config rules, first for try/catch, second for promise chain. Eslint 配置规则,第一个用于 try/catch,第二个用于 promise 链。
"@typescript-eslint/no-implicit-any-catch": ["error", { "allowExplicitAny": true }],
"etc/no-implicit-any-catch": ["error", { "allowExplicitAny": true }]
I have used such approach:我用过这样的方法:
try {
const balance = await this.client.getXrpBalance(this.options.address);
await this.client.disconnect();
return balance;
} catch (error) {
const e = error as Error;
await this.client.disconnect();
throw new GetBalanceError(e.message, 'XRP');
}
With this approach we don't need to modify eslint configurations and as well we don't need to use any type.使用这种方法,我们不需要修改 eslint 配置,也不需要使用任何类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.