TypeScript fails to narrow union of native Error types
paol-imi opened this issue ยท 5 comments
๐ Search Terms
"union native error", "type narrowing union error", "instanceof union error".
๐ Version & Regression Information
Tried in almost every version between 4.0.5 and 5.6.2.
โฏ Playground Link
๐ป Code
function test(t?: unknown) {
if (t instanceof SyntaxError) {
return t;
}
if (t instanceof TypeError) {
return t;
}
throw t;
}
const shouldBeSyntaxErrorOrTypeError = test();
// ?^ SyntaxError๐ Actual behavior
The inferred return type of the test function is SyntaxError.
๐ Expected behavior
The inferred return type of the test function should be SyntaxError | TypeError.
Additional information about the issue
The issue seems to occur with all types of native JavaScript errors, where inferred unions are resolved with just on error (the first defined). Custom errors (classes that extends Error) defined in userland do not appear to suffer from this problem.
This is working as intended. Syntaxerror and TypeError are structurally the same, so subtype reduction (a term you can search for if you want) kicks in and simplifies the type SyntaxError | TypeError to just SyntaxError.
I may understand the dynamics of how these types are simplified but I can't understand how this is the intended behavior. Is it incorrect to expect the behavior I described or is it just a limitation of the actual types definition?
It's a limitation of the type system. It's essentially the same as string | string being reduced to string. Search for "subtype reduction".
The "subtype reduction" dynamic is fine, what I didn't get was the fact that different types of native errors had interchangeable definitions. Thanks!