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-guard-based narrowing of sum types produces the type "never" #17789

Closed
pbazant opened this issue Aug 14, 2017 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@pbazant
Copy link

pbazant commented Aug 14, 2017

TypeScript Version: TS 2.4
Code

class C1 {
    foo: number;
}

class C2 {
    foo: number;
    bar: number;
}

function f_not_C2(a: C1 | C2) {
    if (!(a instanceof C2)) {
        a.foo; // a has type C1, so only foo is available
    }
}

function f_not_C1(a: C1 | C2) {
    if (!(a instanceof C1)) {
        a; // a should have type C2, but has type never!
    }
}

Expected behavior:
The variable "a" in f_not_C1(...) should have type C2.
Actual behavior:
The variable "a" in f_not_C1(...) has type never, making all properties unavailable.

@jcalz
Copy link
Contributor

jcalz commented Aug 15, 2017

Duplicate of #10934 and many others. TypeScript's lack of nominal typing (#202) causes instanceof to behave oddly. Workarounds include adding some optional property to the classes to help TypeScript distinguish them:

class C1 {
    __brand?: 'C1'
    foo: number;
}

class C2 {
    __brand?: 'C2'
    foo: number;
    bar: number;
}

function f_not_C1(a: C1 | C2) {
    if (!(a instanceof C1)) {
        a; // a is C2 now
    }
}

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 16, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Aug 30, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Aug 30, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants