Skip to content

Different narrowing behaviour of user-defined type guards vs discriminated unions #10145

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

Closed
yortus opened this issue Aug 4, 2016 · 2 comments · Fixed by #10194
Closed

Different narrowing behaviour of user-defined type guards vs discriminated unions #10145

yortus opened this issue Aug 4, 2016 · 2 comments · Fixed by #10194
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@yortus
Copy link
Contributor

yortus commented Aug 4, 2016

TypeScript Version: nightly (2.1.0-dev.20160804)

Code

interface A { type: 'A' }
interface B { type: 'B' }

function isA(x: A|B): x is A { return x.type === 'A'; }
function isB(x: A|B): x is B { return x.type === 'B'; }

// Using if/else with type guard functions
function foo1(x: A|B): any {
    x // x is A | B
    if (isA(x)) {
        return x; // x is A
    }
    x // x is B |
    if (isB(x)) {
        return x; // x is B
    }
    x // x is B, but should be never                    <===== (1)
}

// Using if/else with discriminated unions
function foo2(x: A|B): any {
    x // x is A | B
    if (x.type === 'A') {
        return x; // x is A
    }
    x // x is B
    if (x.type === 'B') {
        return x; // x is B
    }
    x // x is never                                     <===== (2)
}

Expected behavior:
x is narrowed to never at both (1) and (2)

Actual behavior:
x is narrowed to never at (2), but at (1) it is narrowed to B.

Notes:
This is carried over from #9260 which is closed. See #9260 (comment)

@yortus yortus changed the title Different narrowing behaviour of type guards vs discriminated unions Different narrowing behaviour of user-defined type guards vs discriminated unions Aug 5, 2016
@yortus
Copy link
Contributor Author

yortus commented Aug 8, 2016

cc: @ahejlsberg

@ahejlsberg
Copy link
Member

@yortus This one is also fixed by #10194.

@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Aug 8, 2016
@ahejlsberg ahejlsberg added this to the TypeScript 2.0.1 milestone Aug 8, 2016
@ahejlsberg ahejlsberg self-assigned this Aug 8, 2016
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Aug 8, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
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.

2 participants