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 does not narrow when the class is intersected with & #50844

Closed
ehmicky opened this issue Sep 19, 2022 · 2 comments Β· Fixed by #51631
Closed

instanceof does not narrow when the class is intersected with & #50844

ehmicky opened this issue Sep 19, 2022 · 2 comments Β· Fixed by #51631
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@ehmicky
Copy link

ehmicky commented Sep 19, 2022

πŸ”Ž Search Terms

instanceof, narrow.

πŸ•— Version & Regression Information

  • This is a crash
  • This is the behavior in every version I tried (from 3.8.3 to to 4.9.0-dev.20220919), and I reviewed the FAQ for entries about it.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface InstanceOne {
  one(): void
}
interface InstanceTwo {
  two(): void
}
const instance = {} as InstanceOne | InstanceTwo

const ClassOneWrong = {} as { new (): InstanceOne } & { foo: true }
if (instance instanceof ClassOneWrong) {
  instance.one() // Property 'one' does not exist, because `instance` is not narrowed down
}

const ClassOneRight = {} as { new (): InstanceOne, foo: true }
if (instance instanceof ClassOneRight) {
  instance.one() // Property 'one' exists and `instance` is narrowed down
}

πŸ™ Actual behavior

instanceof does not narrow down the left side when the right side is a type using &.

πŸ™‚ Expected behavior

It should narrow it down to InstanceOne, and instance.one() should pass.

@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Sep 27, 2022
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Sep 27, 2022
@ahejlsberg ahejlsberg self-assigned this Nov 23, 2022
@ahejlsberg ahejlsberg removed the Help Wanted You can do this label Nov 23, 2022
@ahejlsberg ahejlsberg modified the milestones: Backlog, TypeScript 5.0.0 Nov 23, 2022
@ahejlsberg
Copy link
Member

Another instance of the same issue:

class A { a = 0 }
class B { b = 0 }

function f10(obj: A & { x: string } | B) {
    if (obj instanceof Object) {
        obj;  // B, but should be A & { x: string} | B
    }
    else {
        obj;  // A & { x: string }, but should be never
    }
}

@ehmicky
Copy link
Author

ehmicky commented Nov 29, 2022

Thanks for the fix @ahejlsberg! ❀️

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
4 participants