microsoft/TypeScript

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

https://www.typescriptlang.org/play/?ts=5.6.2#code/GYVwdgxgLglg9mABFApgZygCigfgFyLgDWYcA7mAJSIDeAUIojMItk2BgIaQpwsDKATzBROADwCiAJylwp1eo0ZSUUEFKRQA3A0QBfOruaso7Ljz6IAKoIAOKabPm1dy1es07GB3VAAWsmTIOj5QdiiIaH5wIAA2ACYAQihCIuKOcgDyUjb2GVKIALyIAEruGrkoADxh9paoGAB8dAD0LYg4AHqIqaKSMnJAA

๐Ÿ’ป 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!

nmain commented

You may also be interested in #202, as that handles the difference between a plain object that so happens to have all of the properties of SyntaxError and an object for which instanceof SyntaxError returns true