Skip to content

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

Closed
@louisditzel

Description

@louisditzel

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions