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

Viewed 4821

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.

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)
  }
}

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') {
    /*...*/
  }
}
Related