Closed
Description
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.