Skip to content

Type guard with instanceof fails to narrow type in else block #1719

Closed
@NoelAbrahams

Description

@NoelAbrahams

Hi,

TS Version: 1.4

In the following:

class Bar {
    bar ='bar';
}

class Foo {
    foo = 100;
}

function f1(x: Bar|Foo) {

    if(x instanceof Bar){
        console.log(x.bar);
    }
    else {
        console.log(x.foo); // Error: inferred as Bar|Foo
    }   
}
 f1(new Bar()); // bar
 f1(new Foo()); // 100

is there any reason why in the else block we are failing to narrow the type to Foo?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing codeFixedA PR has been merged for this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions