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
Error interface. 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
catch block to perform paranoid runtime tests for instanceof Error.
- The TypeScript compiler doesn't even support
instanceof Error for transpiled code.
- Relaxing this rule won't cause any trouble; if some people really prefer
unknown they 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:
Suggestion
TypeScript 3.x forbids type annotations in
catchblocks:But TypeScript 4.x relaxed this rule to accept
anyorunknownonly:⭐ Suggestion: Could we relax the rule to allow
Erroras well?Such a declaration would not accurately describe pathological JavaScript code.
But here's why it makes sense anyway:
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.catchblock to perform paranoid runtime tests forinstanceof Error.instanceof Errorfor transpiled code.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
asinstead of:to clarify that technically this is a type cast, while still keeping the syntax concise and intuitive:🔍 Search Terms
catchinstanceofTS19961996✅ Viability Checklist
My suggestion meets these guidelines: