Skip to content

Control flow analysis for discriminated unions breaks when identified by type guards #33903

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
third774 opened this issue Oct 9, 2019 · 2 comments

Comments

@third774
Copy link

third774 commented Oct 9, 2019

TypeScript Version: 3.7-Beta

Search Terms:
type guard discriminated union

Code

const isSomeDiscriminatedUnion = (value: unknown): value is { type: "bar", lol: string } | { type: "baz", omg: string } => true

function test(value: unknown): string {
  if (isSomeDiscriminatedUnion(value)) {
    if (value.type === "bar") {
      // ERROR! type narrowing didn't happen. value is still of type
      // { type: "bar", lol: string } | { type: "baz", omg: string }
      return value.lol
    }
    // ERROR! type narrowing also didn't happen here
    return value.omg
  }
  return ""
}

Expected behavior:
Discriminated unions should be able to have their types narrowed after being identified by a type guard.

Actual behavior:
Discriminated unions do not have their types narrowed after being identified by a type guard.

Playground Link:

https://www.typescriptlang.org/play/index.html?ts=3.7-Beta#code/MYewdgzgLgBAlhAyiAtgUwCIOAJziuMAQyjQBMBVMOcGAXhgAoA3IgGwFc0AuGDsANZgQAdzABKXq05p4EGAG8YUAJ4AHHjABEAIyI4tAGhhsQbXtDxgA5jAC+MAD6Ll6zbqIAvIzFTWLUFa2DnQAfMo4XACwAFCxAGb8wFA0YMpo0CzsXLz8QqISAUGKsTDw8UwIyOhYELj4hCTkVKlZMuLiJTFlZXAVbVwAdKoa9HQMHgadCqU9ZQD08zAAKm4wxDg4ooS2EAAWIBxsZDB7RGoaYIMw0lww+4fHMDqyIBUjaLNziy4fvJM+Uzme6BHb2L49HBoKAcHBpW5oQZAiF2CE-VajDZbERgh5HE5nC5oK43bKyPFPF6+d5uNFLJR-bR6bzGPxFMGo7qQ6Gw+FkwZ+WacspQmFw7RaWKcoA

Related Issues:

@jack-williams
Copy link
Collaborator

I have a fix for this here: #30593.

The issue tracking it is this: #30557.

@third774
Copy link
Author

third774 commented Oct 9, 2019

Oh, awesome! Thanks! 😄

@third774 third774 closed this as completed Oct 9, 2019
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