Skip to content

type guard does not narrow intersection over union #12180

Closed
@siegebell

Description

@siegebell

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions