Skip to content

TypeScript fails to narrow union of native Error typesΒ #60033

Closed
@paol-imi

Description

@paol-imi

πŸ”Ž 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions