Skip to content

Exhaustive check fails to narrow type when union has only 1 type #43056

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Freak613 opened this issue Mar 3, 2021 · 1 comment
Closed

Exhaustive check fails to narrow type when union has only 1 type #43056

Freak613 opened this issue Mar 3, 2021 · 1 comment

Comments

@Freak613
Copy link

Freak613 commented Mar 3, 2021

TypeScript Version: nightly

Code

  type SkippedError = {
   tag: "Skipped"
 };

 const error: SkippedError = {} as any;

 switch (error.tag) {
   case "Skipped":
     const a1: SkippedError = error;
     return 1;
   default:
     const a2: never = error;
     return 0;
 }

Expected behavior:
Exhaustive check should narrow error type to never for a2.

Actual behavior:
Type 'SkippedError' is not assignable to type 'never'.(2322)

The type of error at the a2 is still SkippedError

  • I included happy-path variant of same code in playground link, where union for error has 2 types and code works correctly.
  • The problem reproduces not only for literal types, but also with classes.
  • Trying to narrow type with if has same result.
  • Only working solution in this case is checking classes with instanceof, but can not be applied for literals.

Playground Link: Playground Link

@MartinJohns
Copy link
Contributor

when union has only 1 type

What union? You don't have a union type.

Duplicate of #16976.

@Freak613 Freak613 closed this as completed Mar 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants