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' narrowing works awkwardly with empty object types & primitives #14426

Closed
DanielRosenwasser opened this issue Mar 2, 2017 · 2 comments · Fixed by #19671
Closed
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@DanielRosenwasser
Copy link
Member

Try in the playground.

class Dog {
}

declare let x: Dog | string;

if (x instanceof Dog) {
    x
}
else {
    x.toLowerCase()
}

Expected: No error, first branch's x has type Dog, second branch's x has type string
Actual: Property 'toLowerCase' does not exist on type 'never'. (first branch is string | Dog, second is never)

We should be accounting for primitives a little less sloppily. instanceof checks don't work on primitive types.

@DanielRosenwasser
Copy link
Member Author

DanielRosenwasser commented Sep 16, 2017

Specifically, any changes here should ensure that

function foo(x: number | string) {
    if (x instanceof Number) {
        x
    }
}

x is not narrowed (or is narrowed to never) in the above example.

@DanielRosenwasser
Copy link
Member Author

DanielRosenwasser commented Sep 16, 2017

Actually, we should just issue an error when no constituent of a union is an object type.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants