Course contentsShow
← React
Lesson 2335 of 2,39651. TypeScript with React BasicsFree lesson

Union Types for Variant Props

Use discriminated unions to type components with multiple variant states or modes.

Union Types for Variant Props

What you'll learn: How to use discriminated unions to type components that behave differently based on variant or mode props.

The Problem with Simple Variants

When a component has different "modes" or "variants," each variant often requires different props. A simple variant: string type doesn't capture which props are valid together. You need TypeScript to enforce that certain prop combinations only make sense together.

Discriminated Unions: The Pattern

A discriminated union uses a literal type property (the "discriminant") to differentiate between shapes. TypeScript can then narrow the type based on that property:

type ButtonProps = 
  | { variant: 'primary'; onClick: () => void }
  | { variant: 'link'; href: string }
  | { variant: 'disabled' };

function Button(props: ButtonProps) {
  if (props.variant === 'primary') {
    // TypeScript knows props.onClick exists here
    return <button onClick={props.onClick}>Click</button>;
  }
  if (props.variant === 'link') {
    // TypeScript knows props.href exists here
    return <a href={props.href}>Link</a>;
  }
  return <button disabled>Disabled</button>;
}

// Valid:
<Button variant="primary" onClick={() => {}} />
<Button variant="link" href="/home" />

// TypeScript errors:
<Button variant="primary" href="/home" /> // ❌ href not valid for primary
<Button variant="link" onClick={() => {}} /> // ❌ onClick not valid for link

Why This Matters

The variant property acts as a "tag" that tells TypeScript which shape applies. Each branch of your union can have completely different required props. This prevents impossible states—you can't accidentally pass href to a button variant or onClick to a link variant.

Key Takeaway: Discriminated unions let you enforce that different component variants require different props, making invalid prop combinations impossible at compile time.