Skip to content

Allow : { } / : any type annotations on catch variables #10000

Closed
@RyanCavanaugh

Description

@RyanCavanaugh

It was pointed out in #9999 that catch variables never get narrowed because they're of type any, and you can't change their type because they're not allowed to have type annotations.

This leads to pitfalls like

try {
  // do something
} catch(e) {
  if(e instanceof MyError) {
    console.log(e.filname); // oops.
  }
}

Proposal: allow type annotations on catch variables as long as the annotated type is exactly any or { } (we can't reasonably make this an implicit any according to --noImplicitAny so that behavior would be unchanged). But now "safer" developers can write

try {
  // do something
} catch(e: { }) {
  if(e instanceof MyError) {
    console.log(e.filname); // error, property not found
  }
  console.log(e.filename); // error, forgot to narrow with a guard
}

Alternatively (or in addition to), we could just let catch variables get narrowed despite being any, but this would be a fairly odd carve-out.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions