json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Translate `oneOf` to a discriminated union type

Open JbIPS opened this issue 5 years ago • 1 comments

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.

JbIPS avatar Oct 06 '20 21:10 JbIPS

Hey there! Want to flesh this idea out a bit more? What are some example JSON-Schema inputs, and what outputs will you generate? I'd love to see how this might work for:

  • oneOf with primitive types
  • oneOf with object types that have the same keys, but different value types
  • oneOf with recursively-defined types
  • oneOf with combos of the above

bcherny avatar Nov 25 '20 21:11 bcherny