Skip to content

Add setting useErrorInCatchVariablesΒ #51390

Open
@adamhamlin

Description

@adamhamlin

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions