Sub topic 10
Modeling variants with discriminated unions
This chapter assumes you know TypeScript unions and literal types, and that you can write a typed function component with a props interface. It builds on the earlier chapters on props and native element props.
The problem: props that depend on each other
Some components behave in one of several modes, and each mode needs different props. A button that is either a link or an action is a typical case. A first attempt often makes every mode-specific prop optional:
interface LooseButtonProps {
label: string;
href?: string;
onClick?: () => void;
}
export function LooseButton({ label, href, onClick }: LooseButtonProps) {
if (href) {
return <a href={href}>{label}</a>;
}
return <button onClick={onClick}>{label}</button>;
}This compiles, but the types allow states that make no sense:
<LooseButton label="Go" />has neitherhrefnoronClick.<LooseButton label="Go" href="/" onClick={save} />passes both, andonClickis silently ignored.
The component's behavior is correct only if every caller follows rules that the compiler doesn't know about. A discriminated union moves those rules into the type.
What a discriminated union is
A discriminated union is a union of object types that all share one property, the discriminant. In each member, that property has a different literal type. TypeScript uses the discriminant to work out which member you are holding.
type ActionButtonProps =
| { kind: "link"; href: string; label: string }
| { kind: "action"; onClick: () => void; label: string };
export function ActionButton(props: ActionButtonProps) {
if (props.kind === "link") {
return <a href={props.href}>{props.label}</a>;
}
return <button onClick={props.onClick}>{props.label}</button>;
}Inside the if block, props is narrowed to the "link" member, so props.href is a string. After the block, TypeScript knows only the "action" member remains, so props.onClick is safe. Accessing props.onClick inside the if is a compile error.
What callers see
The union also checks the call site:
import { ActionButton } from "./ActionButton";
export function Toolbar() {
return (
<nav>
<ActionButton kind="link" href="/docs" label="Docs" />
<ActionButton kind="action" onClick={() => alert("Saved")} label="Save" />
{/* Error: Property 'href' is missing in type for the "link" variant */}
{/* <ActionButton kind="link" label="Docs" /> */}
{/* Error: 'href' does not exist on the "action" variant */}
{/* <ActionButton kind="action" href="/docs" onClick={() => {}} label="Save" /> */}
</nav>
);
}Editors also benefit. Once you type kind="link", autocomplete offers href and hides onClick.
Choosing the discriminant
The discriminant must be a literal type that differs between members. These are the usual choices:
- A string literal such as
"link"or"action". This is the most common and reads well in JSX. - A boolean literal such as
multiple: trueandmultiple: false. This works, but string names are clearer once there are three or more variants. - A number literal or
nullandundefined. These work, but they are rarer in props.
The property name is up to you. React code commonly uses kind, variant, type, or status. In a union of props, avoid type if the component also forwards native attributes, because <button type> and <input type> already exist. A name like kind avoids the clash.
Sharing props across variants
Props that every variant needs, such as label, don't have to be repeated. Put them in a base type and intersect it with the union:
type BaseProps = {
label: string;
disabled?: boolean;
};
type ActionButtonProps = BaseProps &
(
| { kind: "link"; href: string }
| { kind: "action"; onClick: () => void }
);
export function ActionButton(props: ActionButtonProps) {
if (props.kind === "link") {
return (
<a href={props.href} aria-disabled={props.disabled}>
{props.label}
</a>
);
}
return (
<button onClick={props.onClick} disabled={props.disabled}>
{props.label}
</button>
);
}The parentheses matter. Without them, & binds tighter than |, and the intersection would apply only to the first member.
Exhaustive checking with never
When you add a variant, you want the compiler to find every place that needs updating. The never type does this. After you handle all members, nothing is left, and the remaining value has type never. A helper that accepts only never turns a forgotten case into a compile error:
type StatusProps =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "success"; data: string[] };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
export function StatusView(props: StatusProps) {
switch (props.status) {
case "idle":
return null;
case "loading":
return <p>Loading…</p>;
case "error":
return <p role="alert">{props.message}</p>;
case "success":
return (
<ul>
{props.data.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
default:
return assertNever(props);
}
}If someone adds { status: "empty" } to StatusProps and does not add a case, the call assertNever(props) fails to compile. The error says the "empty" variant is not assignable to never. At runtime, the throw covers data that bypassed the type system, such as an untyped API response.
Gotchas
Destructuring can lose the link between properties
If you destructure props in the parameter list, the discriminant and the other fields become separate variables:
export function Broken({ kind, href, onClick, label }: ActionButtonProps) {
// Error: 'href' and 'onClick' do not exist on every member of the union
return null;
}Here href and onClick don't exist on every member, so the compiler rejects the destructuring itself. The safe pattern is to accept props, narrow it, and then destructure inside the narrowed branch. TypeScript 4.6 and later can also narrow destructured variables when they come from a const declaration or an unreassigned parameter, but only when the discriminant and the other properties are destructured together from a union-typed value. If narrowing fails for a case you expected to work, fall back to props.kind.
A widened discriminant breaks assignment
When you build props outside JSX, a plain object literal widens kind to string:
const linkProps = { kind: "link", href: "/docs", label: "Docs" };
// <ActionButton {...linkProps} /> // Error: string is not assignable to "link"
const okProps = { kind: "link", href: "/docs", label: "Docs" } as const;
const checkedProps = {
kind: "link",
href: "/docs",
label: "Docs",
} satisfies ActionButtonProps;Either as const or satisfies keeps the literal type. satisfies also checks the object against the union at the point where you write it.
Spreading hides excess properties
JSX attributes written one by one get excess-property checks, so passing onClick to a "link" button is an error. A spread such as {...someObject} skips most of those checks. If the spread object has extra fields, they pass through unchecked.
Forbidding props without a discriminant
Sometimes you want two props to be mutually exclusive but have no natural kind. You can mark the forbidden prop as optional never in each member:
type LabelProps =
| { label: string; ariaLabel?: never }
| { ariaLabel: string; label?: never };This works, but error messages are harder to read than with a discriminant. Use a literal discriminant when you can.
Choosing between approaches
| Approach | Compiler catches invalid combinations | Autocomplete is precise | Cost |
|---|---|---|---|
| Optional props on one interface | No | No | Runtime checks and defensive code |
| Discriminated union | Yes | Yes | An extra `kind` prop that callers must write |
| Optional `never` props | Yes | Partly | Harder error messages |
| Separate components (`LinkButton`, `ActionButton`) | Yes | Yes | More exports, and no single entry point |
A union of more than four or five variants, or variants with very different markup, often reads better as separate components behind a small wrapper. Use a single component when the variants share most of their rendering.
Combining with other chapters
- With native props: a union member can include native attributes, for example
{ kind: "link" } & ComponentPropsWithoutRef<"a">. Define each member from the element it renders. - With reducers: the
Actionunion inuseReduceruses the same technique, withtypeas the discriminant. Narrowing in aswitchworks the same way. - With generics: a union member can be generic, but the discriminant must stay a concrete literal so narrowing still works.
Exercise
A Notice component takes tone: "info" | "error". With tone="error" it must also receive a required onRetry: () => void. With tone="info" it must not accept onRetry. Write the props type, and say which TypeScript feature makes props.onRetry accessible only in the error branch.
Show answer
type NoticeProps = { message: string } & ({ tone: "info" } | { tone: "error"; onRetry: () => void });
The feature is narrowing on a discriminant property. Checking props.tone === "error" narrows props to the member whose tone is the literal "error", so props.onRetry is a () => void inside that branch. Outside it, accessing onRetry is a compile error. Passing onRetry with tone="info" is also rejected at the call site.
Exercise
You add a new variant { status: "empty" } to StatusProps, but the switch in StatusView has no case for it. What happens at compile time, and why?
Show answer
The call assertNever(props) in the default branch fails to compile. After the existing cases are handled, props is still { status: "empty" }, which is not assignable to never. The error points you to the switch that needs a new case.