Description
Suggestion
π Search Terms
catch argument type
catch error type
useUnknownInCatchVariables
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
π Motivating Example
This would be the same kind of setting as useUnknownInCatchVariables
, except simply replace "Unknown" with "Error".
try {
someFuncThatErrors();
} catch (err) {
console.log(err.message); // compiler happy because assumes that `err` is an instance of Error
}
π» Use Cases
Yes, we all know that a maniac could decide to throw a string if they really wanted to--but if that's happening in your project you've got much bigger problems than type safety. TypeScript is about enforcing a contract, so why not allow users to say "all thrown objects will extend Error
"? This will reduce annoying boilerplate/explicit casts in catch
blocks when you just want to access general error properties, or pass err
to a function that expects an Error
.
Obviously this is related to other issues (for example, #20024), but I'm not talking about allowing type annotations in catch variables. Just automatically assuming type Error
and nothing more.