Discriminated union

ReferenceSchema API

s.discriminatedUnion()

One of several object shapes, told apart by a tag: the building block of a page built from sections.

Use it for

  • Sections of a page: a hero, a text block, a gallery
  • A link that is either internal or external
  • Content that comes in variants with different fields

Reference

s.discriminatedUnion(key, ...objects)

schema

One of several object shapes, told apart by a tag field. The first argument names the field; every object sets it to a different s.literal(). Editors pick the variant from a dropdown and then fill in that variant's fields.

In TypeScript, checking the tag narrows the value to its variant, so a switch over it is exhaustive.

In Val Studio

Examples

Sections of a page

page.val.ts
const section = s.discriminatedUnion(
  "type",
  s.object({ type: s.literal("hero"), title: s.string(), image: s.image() }),
  s.object({ type: s.literal("text"), body: s.richtext({ bold: true }) }),
);

const schema = s.object({ sections: s.array(section) });

Rendering it

Page.tsx
function Section({ section }: { section: Section }) {
  switch (section.type) {
    case "hero":
      return <Hero title={section.title} image={section.image} />;
    case "text":
      return <ValRichText>{section.body}</ValRichText>;
  }
}