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.

Activity

self-assigned this
on Feb 2, 2023
added this to the TypeScript 5.0.1 milestone on Feb 2, 2023
ahejlsberg

ahejlsberg commented on Feb 3, 2023

@ahejlsberg
Member

This is an effect of #51631. It fixed isTypeDerivedFrom to correctly handle {}, but turns out narrowTypeByInstanceof was relying on the old inconsistent behavior. That needs fixing too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

    Participants

    @ahejlsberg@dragomirtitian@typescript-bot

    Issue actions

      `instanceof` narrows to `never` on `else` branch for `Function` extending class Β· Issue #52571 Β· microsoft/TypeScript