Skip to content

Type Guards do not narrow this parameters with union types. #14817

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

Closed
louisditzel opened this issue Mar 23, 2017 · 2 comments
Closed

Type Guards do not narrow this parameters with union types. #14817

louisditzel opened this issue Mar 23, 2017 · 2 comments
Labels
Bug A bug in TypeScript
Milestone

Comments

@louisditzel
Copy link

TypeScript Version: 2.2.1

Code

interface A {
    a: number;
}

interface B {
    b: number;
}

function isA(arg: any): arg is A {
    return arg.a !== undefined;
}

function test(arg: A | B) {
    if (isA(arg)) {
        console.log(arg.a);
    } else {
        console.log(arg.b);
    }
}

function testThis(this: A | B) {
    if (isA(this)) {
        console.log(this.a);
    } else {
        console.log(this.b);
    }
}

Expected behavior:
arg is of type A or B in the function test, after passing the type guard.
this is of type A or B in the function testThis, after passing the type guard.

Actual behavior:
arg is the correct type.
this remains of type A | B, so typescript reports an error on both calls to this.a and this.b.

This can be seen in the playground here.

@Andarist
Copy link
Contributor

This was fixed pre-3.3. The issue can be closed. cc @jakebailey

@jakebailey
Copy link
Member

Yeah, this was fixed by #21490 (so is the same as the later #21248).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

7 participants