Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

instanceof type guard does not narrow type of this #5534

Closed
sccolbert opened this issue Nov 4, 2015 · 3 comments
Closed

instanceof type guard does not narrow type of this #5534

sccolbert opened this issue Nov 4, 2015 · 3 comments
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue Help Wanted You can do this

Comments

@sccolbert
Copy link

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;
}
@kitsonk
Copy link
Contributor

kitsonk commented Nov 5, 2015

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.

@ahejlsberg
Copy link
Member

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

@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Nov 5, 2015
@mhegazy mhegazy added this to the Community milestone Dec 8, 2015
@mhegazy mhegazy added the Fixed A PR has been merged for this issue label May 6, 2016
@mhegazy mhegazy modified the milestones: TypeScript 2.0, Community May 6, 2016
@mhegazy
Copy link
Contributor

mhegazy commented May 6, 2016

This should be working as expected in master.

@mhegazy mhegazy closed this as completed May 6, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue Help Wanted You can do this
Projects
None yet
Development

No branches or pull requests

5 participants