Skip to content

instanceof with class-like variable RHS erroneously narrows "else" #13918

@jeffreymorlan

Description

@jeffreymorlan

TypeScript Version: 2.2-rc

Code

class Prop<T> {
    arg: T;
}

interface PropClass<T> {
    new(): Prop<T>;
    prototype: Prop<T>;
}

function check<T>(p: Prop<{}>, specialSubclass: PropClass<T>) {
    if (p instanceof specialSubclass) {
        p.arg; // ok, arg has type T
    } else {
        p.arg; // error here: Property 'arg' does not exist on type 'never'.
    }
}

Expected behavior:
p should have type Prop<{}> in the else block.

Actual behavior:
p has type never in the else block.

Because specialSubclass is a class-like object with instance type Prop, TypeScript is assuming that instanceof returning false implies the object is not a Prop. This is a bad assumption, because in this kind of code instanceof only returns true for members of some (unknown) subclass.

instanceof should narrow the false case only if the RHS is an actual class reference. If it's a variable of a class-like type, it should only narrow the true case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions