Skip to content

instanceof type guard does not narrow type of this #5534

Description

Here's an example which demonstrates (tested on 1.6.2 and current playground):

class Foo {
    a: number;

    foo(): string {
        if (this instanceof Bar) {
            return this.b;  // not okay - `this` typed as Foo
        }
        return '';
    }

    bar(): string {
        let that = this;
        if (that instanceof Bar) {
            return that.b;  // okay - `that` typed as Bar
        }
        return ''
    }
}


class Bar extends Foo {
    b: string;
}

Activity

  1. kitsonk commented on Nov 5, 2015

    @kitsonk
    Contributor

    I think this is all related to polymorphic this #4910 which isn't in 1.6.2 (and playground is 1.6.2). Before that, you couldn't change the this type.

  2. ahejlsberg commented on Nov 5, 2015

    @ahejlsberg
    Member

    Type guards currently only affect parameters and local variables, but I agree it seems reasonable to also have them apply to this. Kitson Kelly (@kitsonk) No, not related to the polymorphic this feature, the restriction is still there in current builds.

  3. added this to the milestone on Dec 8, 2015
  4. modified the milestones: TypeScript 2.0, on May 6, 2016
  5. mhegazy commented on May 6, 2016

    @mhegazy
    Contributor

    This should be working as expected in master.

  6. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issueHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions