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

Narrow union type with 'in' operator #19754

Closed
jovdb opened this issue Nov 5, 2017 · 3 comments
Closed

Narrow union type with 'in' operator #19754

jovdb opened this issue Nov 5, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@jovdb
Copy link

jovdb commented Nov 5, 2017

Like we can narrow down union types with typeof and instance of, it would be nice if it could also be narrowed with the javascript in operator.

Code

type Message1 = { name: "foo"};
type Message2 = { name: "personAdded", personId: string, fullName: string};
type Message3 = { name: "personSelected", personId?: string };
type AnyMessage = Message1 | Message2 | Message3;

function handleMessage(message: AnyMessage) {

    // message can be: Message1 | Message2 | Message3
    if ("personId" in message) {

        // narrowed to: Message2 | Message3
        switch (message.name) {
            case "personAdded":    console.log(`Person added: ${message.fullName}`); break;
            case "personSelected": console.log("Person selection changed"); break;
            default: exhaustiveFail(message); break; // error: Message1 is not handled
        }
    }    
};

function exhaustiveFail(x: never): never {
    throw new Error(`Unexpected object: ${x}`);
}

When using an exhaustive switch/if, it would allow us to reduce the union type down to only the types that can have the specified property.

Remark
What to do with numbers and symbols?

const a = ["foo", 42];
if (0 in a) {...}
if (Symbol.iterator in a) {...}
@jovdb
Copy link
Author

jovdb commented Nov 5, 2017

Can be marked as duplicate, found a similar issue: #10485, and #15256

@DanielRosenwasser
Copy link
Member

Thanks for digging those up @jovdb.

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Nov 6, 2017
@typescript-bot
Copy link
Collaborator

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

@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