Skip to content

Allow "catch (e as Error)" instead of "catch (e: unknown)" #42596

@octogonz

Description

@octogonz

Suggestion

TypeScript 3.x forbids type annotations in catch blocks:

try {
  // ...
} catch (e: Error) { // <-- TS1996 "Catch clause variable cannot have a type annotation"
  // ...
}

But TypeScript 4.x relaxed this rule to accept any or unknown only:

try {
  // ...
} catch (e: Error) { // <-- TS1996 "Catch clause variable type annotation must be 'any' or 'unknown' if specified"
  // ...
}

Suggestion: Could we relax the rule to allow Error as well?

Such a declaration would not accurately describe pathological JavaScript code.

But here's why it makes sense anyway:

  1. In a professional code base, thrown objects always implement the Error interface. We have lint rules that enforce this. And external packages generally follow this rule as well, at least the kind we'd use for professional work.
  2. It's wasteful for every single catch block to perform paranoid runtime tests for instanceof Error.
  3. The TypeScript compiler doesn't even support instanceof Error for transpiled code.
  4. Relaxing this rule won't cause any trouble; if some people really prefer unknown they can enable it via a lint rule like no-implicit-any-catch without any involvement from the compiler.

Alternate syntax

In the thread below, @MickeyPhoenix suggested to use as instead of : to clarify that technically this is a type cast, while still keeping the syntax concise and intuitive:

try {
  // ...
} catch (e as Error) {
  // ...
}

🔍 Search Terms

catch instanceof TS1996 1996

✅ 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.

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