Skip to content

instanceof type inference broken in an "if -> else if -> else if" chain #11965

Description

@stkomarov

TypeScript Version: "typescript@2.0.6"

// A *self-contained* demonstration of the problem follows...
class Action1 {
  public constructor(public propA: string) {}
}

class ActionX {

}

class Action2 {
  public constructor(public propB: string) {}
}

class FooBar {

  public handleAction(action: Object): void {
    if (action instanceof Action1) {
      console.log(action.propA); // works
    } else if (action instanceof ActionX) {
      // The presense of this empty clause is essential
    } else if (action instanceof Action2) {
      console.log(action.propB); // throws compile error: Error TS2339: Property 'propB' does not exist on type 'never'.
    }
  }
}

Expected behavior:
The code to compile without an error.
Actual behavior:
The code above throws a compile error:
Error TS2339: Property 'propB' does not exist on type 'never'.

A workaround for the issue is to use an explicit cast for the last "else if" clause:

    } else if (action instanceof Action2) {
      const a = action as Action2;
      console.log(a.propB); // now it works
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

FixedA PR has been merged for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions