Skip to content

Translate oneOf to a discriminated union type #343

@JbIPS

Description

@JbIPS

The oneOf properties is described in README as Not expressible in TypeScript.

I recently discovered the discriminated union type with a mutual exclusion, which fit perfectly with a XOR:

type MenuItemXor = {
    title: string;
    icon: string;
} & (
        | { component: object; click?: never }
        | { component?: never; click: boolean }
    )

let testXor: MenuItemXor;
testXor = { title: "t", icon: "i" } // error, none are set
testXor = { title: "t", icon: "i", component: {} } // ✔
testXor = { title: "t", icon: "i", click: true } // ✔
testXor = { title: "t", icon: "i", click: true, component: {} } // error, both are set

This is well explained in this SO answer and seems to me a perfect fit for oneOf.

I can work on a PR if you feel OK with this feature.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions