Skip to content

Type narrowing on a property with disjoint set of values #16580

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
colltoaction opened this issue Jun 16, 2017 · 2 comments
Closed

Type narrowing on a property with disjoint set of values #16580

colltoaction opened this issue Jun 16, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@colltoaction
Copy link

TypeScript Version: 2.3.4 / Current playground version

Code

export interface AuthenticatedProfile {
    readonly userId: string;
    readonly name: string;
}
export interface AnonymousProfile {
    readonly userId: undefined;
    readonly otherProp: string;
}
export type Profile = AnonymousProfile | AuthenticatedProfile;

function handleProfile(prof: Profile) {
    if (prof.userId !== undefined) {
        console.log(prof.name);
    }
}

Expected behavior:

Code would compile, since by checking that the userId property is not undefined we definitely know we are handling an AuthenticatedProfile instance.

Actual behavior:

Type checks fail and you need workarounds such as the ones on this question: https://stackoverflow.com/q/44583342/625581.

What makes me think this is a bug (or at least can be added as a feature) is that this other similar code works. I've read the handbook and it seems that casting is an option, but the userId property is already part of both instances and I wouldn't want to add the boilerplate of casting when there's information right there.

@ahejlsberg
Copy link
Member

Duplicate of #12600.

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

mhegazy commented Aug 17, 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 17, 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

3 participants