Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the @typescript-eslint/no-unsafe-member-access rule on catch(err) blocks?

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.

enter image description here

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.

like image 476
cbdeveloper Avatar asked Mar 03 '21 17:03

cbdeveloper


People also ask

Is it harder to write try/catch blocks in typescript?

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.

Does typescript-eslint support ESLint rules?

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.

Should you allow member access on any type in typescript?

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.

What do the errors in ESLint mean?

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.


2 Answers

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)
  }
}
like image 152
Yonghui Lin Avatar answered Sep 29 '22 11:09

Yonghui Lin


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') {
    /*...*/
  }
}
like image 37
HaveSpacesuit Avatar answered Sep 29 '22 11:09

HaveSpacesuit