Skip to content

discriminated union using non-literal-typeΒ #59151

Closed as not planned
Closed as not planned
@kim-jaedeok

Description

@kim-jaedeok

πŸ”Ž Search Terms

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

πŸ•— Version & Regression Information

[email protected]

⏯ 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

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