Skip to content

discriminated union using non-literal-type #59151

Description

🔎 Search Terms

"discriminated union", "discriminated union using non-literal-type"

🕗 Version & Regression Information

typescript@5.2.2

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAYg9nKBeKBvAUFKBDAXFAZ2ACcBLAOwHMBuTKAI3yLKtoF9bRIoAhbY5Gjp4o5AK4BbehGK0sjUZOmz0HdOi7QAqhTjlB8RAB9e-WugBmY8gGNgpPVGAQiAClQ4ANAyht8O8j0ASiEsUgsoV004COxkJBQAImYKSkSQjCwsbDks+ly2VXQgA

💻 Code

type Foo = {
  a: string;
  b: string;
};
type Bar = {
  a: number;
  b: number;
};

type Uinon = Foo | Bar;

function test({ a, b }: Uinon) {
  if (typeof a === "string") {
    a; // a is string
    b; // b is string | number
  }
}

🙁 Actual behavior

Inside the test function, b's type does not narrow down to string when a type is string.
why discriminated union only works with literal type?

🙂 Expected behavior

i think b's type should be string

Additional information about the issue

https://stackoverflow.com/questions/78707864/type-narrowing-doesnt-work-when-using-a-non-type-literal-field-as-a-tag/78707873#78707873

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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