Skip to content

Wrong type narrowing when types are compatibles #11664

Closed
@akarzazi

Description

@akarzazi

TypeScript Version: 2.0.3

Code

class Result1 {
    readonly value1: number;

    constructor(value1: number) {
        this.value1 = value1;
    }
}

class Result2 {
    readonly value1: number;
    readonly value2: number;

    constructor(value1: number, value2: number) {
        this.value1 = value1;
        this.value2 = value2;
    }
}

function someFunction(result: Result1 | Result2) {
    if (result instanceof Result1) {
        // result is still Result1 | Result2
        console.log("1");
    }
    else {
        // result is never ! this is wrong !
        console.log("2");
    }
}

// this will output 2 !
someFunction(new Result2(9,9))

Expected behavior:
instance of type guard should not care about type compatibility
Actual behavior:
Wrong assertion by the compiler.

Metadata

Metadata

Assignees

No one assigned

    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