Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
dragomirtitian opened this issue Feb 2, 2023 · 1 comment Β· Fixed by #52592
Closed

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

dragomirtitian opened this issue Feb 2, 2023 · 1 comment Β· Fixed by #52592
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@dragomirtitian
Copy link
Contributor

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.

@ahejlsberg ahejlsberg self-assigned this Feb 2, 2023
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Feb 2, 2023
@ahejlsberg ahejlsberg added this to the TypeScript 5.0.1 milestone Feb 2, 2023
@ahejlsberg
Copy link
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
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants