JavaScript and React course Β· Module 12: React and TypeScript

Discriminated Unions - Component Variants

5 min read Β·
In this lesson5

A cosmic object card receives a planet one time, a star the next, an asteroid after that. You throw all fields into one type, mark them optional, and a month later nobody remembers whether a star can have moons. In space, different objects require different handling - a planet, a star, and an asteroid are different entities with different properties. Discriminated unions let TypeScript distinguish object variants based on a single field.

The Problem - Different Data Shapes

Imagine a component that displays different types of cosmic objects. Each type has different fields. The simplest solution looks innocent:

// BAD - unclear which fields are available
interface SpaceObject {
  type: string;
  name: string;
  radius?: number;
  temperature?: number;
  composition?: string[];
  orbitalPeriod?: number;
}

function SpaceInfo({ obj }: { obj: SpaceObject }) {
  // You must check each field separately
  if (obj.radius) { /* ... */ }
  if (obj.temperature) { /* ... */ }
  // Easy to make mistakes!
}

This type lets you create a "planet" with a star's temperature and no radius - the compiler can't catch it, because everything is optional. On top of that, if (obj.radius) skips a planet with a radius of 0, because zero is falsy.

The Solution - Discriminated Unions

Instead of one interface with optional fields, we create separate interfaces connected by a common field (the discriminator). The key is that the discriminator has a literal type: not any string, but one specific string, for example kind: "planet". That string is how TypeScript recognizes the variant.

// Each type has a common 'kind' field with a different value
interface PlanetData {
  kind: "planet";
  name: string;
  radius: number;
  habitable: boolean;
  moons: number;
}

interface StarData {
  kind: "star";
  name: string;
  temperature: number;
  luminosity: number;
  spectralClass: string;
}

interface AsteroidData {
  kind: "asteroid";
  name: string;
  composition: string[];
  diameter: number;
}

Now we join the three interfaces with | into one union type. A value of type SpaceObject is exactly one of the three variants, never a mix:

// Union type - the object can be one of three types
type SpaceObject = PlanetData | StarData | AsteroidData;

A planet without radius or a star with a moons field no longer compiles. All fields in the variants are required - the optionality is gone, because each variant describes only what it really has.

Type Narrowing

TypeScript automatically narrows the type based on the discriminator field. When you check obj.kind in a switch statement, inside each case the compiler knows which variant you're working with:

function SpaceInfo({ obj }: { obj: SpaceObject }) {
  // Common field - available for all variants
  const header = <h2>{obj.name}</h2>;

  // Switch on the discriminator
  switch (obj.kind) {
    case "planet":
      // TypeScript KNOWS that obj is PlanetData
      return (
        <div>
          {header}
          <p>Radius: {obj.radius} km</p>
          <p>Moons: {obj.moons}</p>
          <p>{obj.habitable ? "Habitable" : "Uninhabitable"}</p>
        </div>
      );
    case "star":
      // TypeScript KNOWS that obj is StarData
      return (
        <div>
          {header}
          <p>Temperature: {obj.temperature}K</p>
          <p>Class: {obj.spectralClass}</p>
        </div>
      );
    case "asteroid":
      // TypeScript KNOWS that obj is AsteroidData
      return (
        <div>
          {header}
          <p>Diameter: {obj.diameter} km</p>
          <p>Composition: {obj.composition.join(", ")}</p>
        </div>
      );
  }
}

Before the switch, only the common name field is available. In the "star" branch, reading obj.moons is an error, because stars don't have moons. What did NOT change: in running code this is an ordinary switch on a string - all the magic happens in the compiler.

UI Component Variants

Discriminated unions are ideal for creating UI component variants. A success alert needs only a message, but an error alert must receive a retry action. The type can enforce that:

// Alert variants
type AlertProps =
  | { variant: "success"; message: string }
  | { variant: "error"; message: string; retryAction: () => void }
  | { variant: "warning"; message: string; dismissable: boolean }
  | { variant: "info"; message: string; link?: string };

This time the variants are written inline, without separate interfaces, and the discriminator is variant. The component takes the whole props without destructuring, because destructuring before checking the variant makes narrowing harder. We build CSS classes with a template string:

function Alert(props: AlertProps) {
  const baseClass = "alert";

  switch (props.variant) {
    case "success":
      return <div className={`${baseClass} success`}>{props.message}</div>;
    case "error":
      return (
        <div className={`${baseClass} error`}>
          {props.message}
          <button onClick={props.retryAction}>Retry</button>
        </div>
      );
    case "warning":
      return (
        <div className={`${baseClass} warning`}>
          {props.message}
          {props.dismissable && <button>Dismiss</button>}
        </div>
      );
    case "info":
      return (
        <div className={`${baseClass} info`}>
          {props.message}
          {props.link && <a href={props.link}>Learn more</a>}
        </div>
      );
  }
}

The call <Alert variant="error" message="Failure" /> without retryAction is rejected - the component won't let you build an error alert without a rescue button.

Exhaustive Checking - Never Miss a Variant

What if a year from now someone adds a "comet" variant and forgets to handle it? The never type helps: it means a value that cannot exist. When a switch handles every variant, the variable in the default branch has the type never. The assertNever function accepts only never, so every unhandled variant becomes a compile error:

// Helper function - TypeScript will report an error if you don't handle all variants
function assertNever(value: never): never {
  throw new Error(`Unhandled variant: ${value}`);
}

function getLabel(obj: SpaceObject): string {
  switch (obj.kind) {
    case "planet": return "Planet";
    case "star": return "Star";
    case "asteroid": return "Asteroid";
    default: return assertNever(obj); // error if you add a new type and don't handle it
  }
}

After adding CometData to the union, TypeScript points at the assertNever line before the code reaches the crew. The throw only fires if invalid data arrives from outside at runtime. My advice: add assertNever to every switch on a discriminator - it's a cheap insurance policy. In the next lesson a discriminated union will describe the actions in useReducer.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Discriminated union - different cosmic objects
interface PlanetData {
  kind: "planet";
  name: string;
  radius: number;
  habitable: boolean;
  moons: number;
}

interface StarData {
  kind: "star";
  name: string;
  temperature: number;
  luminosity: number;
  spectralClass: "O" | "B" | "A" | "F" | "G" | "K" | "M";
}

interface AsteroidData {
  kind: "asteroid";
  name: string;
  diameter: number;
  composition: string[];
  dangerLevel: 1 | 2 | 3 | 4 | 5;
}

type SpaceObject = PlanetData | StarData | AsteroidData;

// Component with type narrowing
function SpaceCard({ obj }: { obj: SpaceObject }) {
  const getIcon = (): string => {
    switch (obj.kind) {
      case "planet": return "●";
      case "star": return "*";
      case "asteroid": return "β€’";
    }
  };

  const renderDetails = (): React.ReactNode => {
    switch (obj.kind) {
      case "planet":
        return (
          <>
            <p>Radius: {obj.radius} km</p>
            <p>Moons: {obj.moons}</p>
            <span className={"badge " + (obj.habitable ? "green" : "red")}>
              {obj.habitable ? "Habitable" : "Uninhabitable"}
            </span>
          </>
        );
      case "star":
        return (
          <>
            <p>Temperature: {obj.temperature}K</p>
            <p>Luminosity: {obj.luminosity}x Sun</p>
            <span className="badge blue">Class {obj.spectralClass}</span>
          </>
        );
      case "asteroid":
        return (
          <>
            <p>Diameter: {obj.diameter} km</p>
            <p>Composition: {obj.composition.join(", ")}</p>
            <span className="badge orange">
              Danger: {"!".repeat(obj.dangerLevel)}
            </span>
          </>
        );
    }
  };

  return (
    <div className={"space-card " + obj.kind}>
      <div className="card-header">
        <span className="icon">{getIcon()}</span>
        <h3>{obj.name}</h3>
        <span className="kind">{obj.kind}</span>
      </div>
      <div className="card-body">{renderDetails()}</div>
    </div>
  );
}

function App() {
  const [objects] = useState<SpaceObject[]>([
    { kind: "planet", name: "Kepler-442b", radius: 8200, habitable: true, moons: 2 },
    { kind: "star", name: "Betelgeuse", temperature: 3500, luminosity: 126000, spectralClass: "M" },
    { kind: "asteroid", name: "Apophis", diameter: 370, composition: ["iron", "nickel", "silicon"], dangerLevel: 4 },
    { kind: "planet", name: "HD 209458 b", radius: 94000, habitable: false, moons: 0 },
    { kind: "star", name: "Sirius", temperature: 9940, luminosity: 25, spectralClass: "A" },
    { kind: "asteroid", name: "Ceres", diameter: 939, composition: ["ice", "rock", "minerals"], dangerLevel: 1 },
  ]);

  const [filter, setFilter] = useState<SpaceObject["kind"] | "all">("all");

  const filtered = filter === "all"
    ? objects
    : objects.filter(obj => obj.kind === filter);

  return (
    <div className="app">
      <h1>Cosmic Object Catalog</h1>
      <div className="filters">
        {(["all", "planet", "star", "asteroid"] as const).map(f => (
          <button
            key={f}
            className={"filter-btn " + (filter === f ? "active" : "")}
            onClick={() => setFilter(f)}
          >
            {f === "all" ? "All" : f === "planet" ? "Planets" : f === "star" ? "Stars" : "Asteroids"}
          </button>
        ))}
      </div>
      <div className="cards">
        {filtered.map((obj, i) => <SpaceCard key={i} obj={obj} />)}
      </div>
    </div>
  );
}

export default App;

Remember: the discriminator is the object's identification signal - read it, and TypeScript switches the sensors to the right variant by itself.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What type must the discriminator field (e.g. kind) be in a discriminated union for TypeScript to automatically narrow the type?

  2. 2. What is a discriminated union in TypeScript?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps for creating and using a discriminated union in the correct order:

  • Code editor

    Discriminated union for component variants

  • Click in order

    Arrange the syntax of the assertNever function for exhaustive checking:

  • Horizontal ordering

    Arrange the syntax for defining a union type from three interfaces:

  • Code editor

    Generic discriminated union for asynchronous states

  1. QuestionDiscriminator Field in Union Type
  2. QuestionDiscriminated Union in TypeScript
  3. Put in orderType Narrowing with Discriminated Union
  4. Coding taskPractice: Component with Discriminated Unions
  5. QuestionGenerics vs Concrete Types
  6. Click in orderThe assertNever Function
  7. Put in orderUnion Type Definition
  8. Coding taskPractice: Loading States with Discriminated Union

Useful articles