Skip to content

type guard does not narrow intersection over union #12180

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
siegebell opened this issue Nov 11, 2016 · 3 comments
Closed

type guard does not narrow intersection over union #12180

siegebell opened this issue Nov 11, 2016 · 3 comments
Labels
Fixed A PR has been merged for this issue

Comments

@siegebell
Copy link

TypeScript Version: 2.0.8
Code

interface A {tag: "a", a};
interface B {tag: "b", b};
interface C {c};
type ABC1 = (A & C) | (B & C);
let y : ABC1 = {tag:"a", a: "foo", c: "bar"}
if(y.tag === "a")
  y.a // this is accepted
type ABC2 = (A | B) & C;
let x : ABC2 = {tag:"a", a: "foo", c: "bar"}
if(x.tag === "a")
  x.a // but this is currently an error :(

Expected behavior:
After checking x.tag==="a", the type of x should be narrowed to A & C
Actual behavior:
There is no narrowing, so x.a results in a type error.

A workaround is given by ABC1, but in practice, this results in very long and redundant type definitions.

@siegebell
Copy link
Author

Hmm. It seems that ABC1 and ABC2 are not even considered equivalent types:

x = y; // okay: y:ABC1 is a subtype of x:ABC2
y = x; // error

Is this intended behavior? I.e. is there a case where x and y might not be compatible?

@RyanCavanaugh
Copy link
Member

This has been fixed by #11717

@RyanCavanaugh RyanCavanaugh added the Fixed A PR has been merged for this issue label Nov 11, 2016
@siegebell
Copy link
Author

@RyanCavanaugh phew -- Thanks!

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants