I've recently added eslint
to my Typescript codebase.
By default, it enables the @typescript-eslint/no-unsafe-member-access
.
And all of sudden, I'm getting tons of lint errors on my catch blocks.
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)
.
I don't want to disable the rule completely, neither I want to add eslint-disable
on every catch(err)
block.
Although its harder in TypeScript we can still make the most of it and manage to write clean try/catch blocks. Thanks for reading! Be sure to follow me on Medium as I try to publish content often.
If you are using ESlint, but not typescript-eslint, you may be aware that you can add rules in package.json under eslintConfig. However, typescript-eslint does not look at the package.json for rules and currently requires an actual eslintrc.* file.
Despite your best intentions, the any type can sometimes leak into your codebase. Member access on any typed variables is not checked at all by TypeScript, so it creates a potential safety hole, and source of bugs in your codebase. This rule disallows member access on any variable that is typed as any.
The errors mean, that you try to access a property (or member) of an object with type any. any in TS gives you no clues or knowledge about the values behind the variables. ESLint displays an error, since accessing members of objects with type any can lead to unwanted (and maybe undetected) bugs.
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
. We can use instanceof-narrowing to avoid such a warning
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') {
/*...*/
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With