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