Sub topic 10
Modeling variants with discriminated unions
This chapter assumes you know TypeScript unions and interfaces, and that you can write a typed function component with props. It covers how to describe a component whose props change shape depending on one "kind" value.
The problem with optional props
Suppose a button can be either a link or an action. A common first attempt makes every prop optional:
interface LooseProps {
label: string;
href?: string;
onClick?: () => void;
}This type accepts { label: "Go" } with neither prop. It also accepts both href and onClick together. The compiler cannot tell you which combinations are valid, so the component must guard against every case at runtime.
A discriminated union
A discriminated union is a union of object types that share one property with a literal type. That shared property is the discriminant. Checking it tells TypeScript which member of the union you have.
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 if, only the action member remains, so props.onClick is available.
What the caller sees
The compiler now rejects invalid usage:
<ActionButton kind="link" href="/home" label="Home" /> // ok
<ActionButton kind="action" onClick={save} label="Save" /> // ok
<ActionButton kind="link" label="Home" /> // error: href is missing
<ActionButton kind="action" href="/home" label="Go" /> // error: href does not existThe editor also autocompletes only the props that belong to the chosen kind.
Common mistakes
- Destructuring too early. Narrowing works on
props.kind. In older TypeScript versions, destructuring{ kind, href }in the parameter list loses the link between the two values. Keeppropswhole until you have checkedkind. Recent TypeScript versions can narrow destructured parameters in some cases, but the rule above is safe everywhere. - Using
stringfor the discriminant. If you writekind: string, narrowing cannot work. Use literal types such as"link". - Optional discriminants. A
kind?: "link"property weakens narrowing. Make the discriminant required, or handle the default deliberately. - Repeating shared props. Put common props in a base type and intersect it:
type BaseProps = { label: string; disabled?: boolean };
type ActionButtonProps = BaseProps &
(
| { kind: "link"; href: string }
| { kind: "action"; onClick: () => void }
);Exhaustiveness checking
When you add a third variant, you want the compiler to point at every place that must handle it. Assign the leftover value to never in a final branch:
function describe(props: ActionButtonProps): string {
switch (props.kind) {
case "link":
return `Link to ${props.href}`;
case "action":
return "Runs an action";
default: {
const unreachable: never = props;
return unreachable;
}
}
}If you add { kind: "toggle" } to the union and forget a case, the never assignment fails to compile. The same idea powers the useReducer action unions you will meet in a later chapter.
Exercise
A Notice component takes tone: "info" | "error". When tone is "error", it must also receive a retry: () => void function. When tone is "info", retry must not be allowed. Write the props type.
Show answer
type NoticeProps = { message: string } & ({ tone: "info" } | { tone: "error"; retry: () => void }); The literal tone is the discriminant. Passing retry with tone="info" is an error, and omitting retry with tone="error" is also an error.