-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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:
- In a professional code base, thrown objects always implement the
Errorinterface. 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. - It's wasteful for every single
catchblock to perform paranoid runtime tests forinstanceof Error. - The TypeScript compiler doesn't even support
instanceof Errorfor transpiled code. - Relaxing this rule won't cause any trouble; if some people really prefer
unknownthey 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.
AlCalzone, MickeyPhoenix, KevinTCoughlin, iclanton, AndrewPomorski and 41 moreMartinJohns, weslord, hiepxanh and ExE-BossPatrikValkovic
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript