Skip to content

instanceof narrows to never on else branch for Function extending classΒ #52571

Closed
@dragomirtitian

Description

@dragomirtitian

Bug Report

πŸ”Ž Search Terms

insatnceof extends function

πŸ•— Version & Regression Information

  • This changed between versions 5.0.0-dev.20221129 and 5.0.0-dev.20221130

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class PersonMixin extends Function {
    public [Symbol.hasInstance](o: any) {
        return typeof o === "object" && o !== null && o instanceof Person;
    }    
}
const cls = new PersonMixin();

class Person {
    work(): void { console.log("work") }
    sayHi(): void { console.log("Hi") }
}
class Car {
    sayHi(): void { console.log("Wof Wof") }
}

function test(o: Person | Car) {
    if (o instanceof cls) {
        console.log("Is Person");
        (o as Person).work()
    }
    else {
        console.log("Is Car")
        o.sayHi(); //o is never in 5.0. Was Person | Car in 4.9
    }
}
test(new Person)
test(new Car)

πŸ™ Actual behavior

o is never on the else branch. causing an error

πŸ™‚ Expected behavior

o is Person | Car as it was in 4.9 since the type guard doesn't really say a lot about the type of o in the type system.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions