[英]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
,甚至null
或undefined
。 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.