Skip to content

Allow unknown type annotation on catch clause variable #36775

Closed

Description

Search Terms

catch clause unknown exception

Suggestion

Now any kind of type annotation on catch clauses is not allowed.
In my understanding, it's because that it's unsafe to annotate like catch (err: SpecialError) since any value will be captured actually.

However, due to the type of err is any, it's also not type safe.

So I suggest to allow annotating unknown , as most safe typing.

(And annotation with any other type won't be allowed as is)

Examples

try {
  throw 42;
} catch (err) {
  console.error(err.specialFunction()); 
}

can be written safer as

try {
  throw 42;
} catch (err: unknown) {
  if (err instanceof SpecialError) {
    console.error(err.specialFunction()); 
  } else {
    ...
  }
}

Related Issue

#20024

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions