Skip to content

TypeScript should respect "instanceof" in logical expressions #31291

Closed
@slavafomin

Description

@slavafomin

Hello!

Thank you for your hard work.

Please, consider this code:

class Foo { 
    foo: string;
}
class Bar {
    bar: string;
}

function foo(value: Foo | Bar) {
    const isFoo = value instanceof Foo;
    const isBar = !isFoo && value.bar; // <-- causes error
}

The line above throws an error:

Property 'bar' does not exist on type 'Foo | Bar'.
Property 'bar' does not exist on type 'Foo'.

However, if I replace the logical variable with the expression directly, it works:

const isBar = !(value instanceof Foo) && value.bar;

The isFoo variable in my example is a boolean constant, it's value can't change, so I believe it should be statically analyzable.

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