Skip to content

Broken instanceof type guarding #17424

Closed
Closed
@nin-jin

Description

@nin-jin

TypeScript Version: 2.4.0

Code

class A { foo: string }
class B { bar: string }

function test(x : A | B) {
  if (x instanceof A) {
    console.log(x.foo);
  } else {
    console.log(x.bar); // Expected typeof x == A|B
  }
}

test({ foo: "Hello, world" }); // undefined

Expected behavior:

Error at this line:

    console.log(x.bar);

Because x can implement A (and not implement B) interface but do not be instance of A class.

Actual behavior:

No errors. Wrong result.

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