-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow : { }
/ : any
type annotations on catch variables
#10000
Comments
🎈 🎉 10,000th issue 🎉 🎈 |
Related discussion in #8677 |
You could also see it the other way, that type guards were originally intended to work everywhere, but #1433 created a special carve-out where type guards no longer work (for pragmatic reasons). In that light, having type guards still work in the |
A consideration here is discoverability. The following gives no compiler errors, so the author may mistakenly believe that TypeScript is type-checking the code when it is actually not: try {
foo();
}
catch (ex) {
if (ex instanceof FooError) {
/* recover from FooError */
ex.foo // NOT typechecked - won't find typos, won't be picked up in refactorings
...
}
else {
throw ex;
}
} It seems a bit magical and arbitrary that if we take the same code, but change How would a user know that they need to add the annotation if the compiler doesn't complain either way? Often people don't realise there is something wrong with their code until they see a compile-time or runtime error, and with TypeScript the main benefit is to get more of the former and less of the latter. |
This will be handled be #9999 |
It was pointed out in #9999 that
catch
variables never get narrowed because they're of typeany
, and you can't change their type because they're not allowed to have type annotations.This leads to pitfalls like
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 writeAlternatively (or in addition to), we could just let
catch
variables get narrowed despite beingany
, but this would be a fairly odd carve-out.The text was updated successfully, but these errors were encountered: