How to Avoid any in React Applications :👈 👉:Common TypeScript Errors in React

Discriminated Unions for React Component Props

Discriminated Unions for React Component Props in TypeScript

1. What Are Discriminated Unions?

A discriminated union is a TypeScript feature that allows a variable or component prop to have multiple possible shapes, with a common property (called a discriminant) identifying which shape is being used.

In React, discriminated unions are useful when a component supports different modes or variations, and each mode requires different props.

For example, consider a Button component that supports two modes:

  • Link mode: Requires an href property.
  • Action mode: Requires an onClick callback.

Instead of making every property optional, we can use a discriminated union to ensure that each mode receives the correct properties.

2. Problem Without Discriminated Unions

Consider a component with multiple optional properties.

Example:
interface ButtonProps {
    type: "link" | "action";
    href?: string;
    onClick?: () => void;
    label: string;
}
function Button(props: ButtonProps) {
    return (
        <button onClick={props.onClick}>
            {props.label}
        </button>
    );
}

This approach has some problems:

// Valid
<Button
    type="link"
    href="/home"
    label="Home"
/>
// Invalid combination, but TypeScript allows it
<Button
    type="link"
    onClick={() => alert("Clicked")}
    label="Home"
/>
// Missing href, but TypeScript allows it
<Button
    type="link"
    label="Home"
/>

The problem is that TypeScript treats href and onClick as independent optional properties. It does not enforce which properties belong to each mode.

3. Solution: Use Discriminated Unions

Define separate types for each variation and combine them using a union.

Example:
type ButtonProps =
    | {
        type: "link";
        href: string;
        label: string;
      }
    | {
        type: "action";
        onClick: () => void;
        label: string;
      };

Here:

  • type is the discriminant property.
  • "link" identifies the link variation.
  • "action" identifies the action variation.
  • Each variation has its own required properties.

Now TypeScript enforces the correct properties for each variation.

Valid usage:
<Button
    type="link"
    href="/home"
    label="Home"
/>
<Button
    type="action"
    onClick={() => alert("Clicked")}
    label="Submit"
/>
Invalid usage:
// Error: href is required for link mode
<Button
    type="link"
    label="Home"
/>
// Error: onClick is required for action mode
<Button
    type="action"
    label="Submit"
/>

4. Implementing the React Component

Inside the component, use the discriminant property to identify which variation is active.

Example:
type ButtonProps =
    | {
        type: "link";
        href: string;
        label: string;
      }
    | {
        type: "action";
        onClick: () => void;
        label: string;
      };
function Button(props: ButtonProps) {
    if (props.type === "link") {
        return (
            <a href={props.href}>
                {props.label}
            </a>
        );
    }
    return (
        <button onClick={props.onClick}>
            {props.label}
        </button>
    );
}

TypeScript automatically narrows the type of props based on the value of props.type.

  • When type === "link", TypeScript knows that href exists.
  • Otherwise, TypeScript knows that onClick exists.

5. How Type Narrowing Works

Type narrowing means TypeScript reduces a union of possible types to the specific type identified by a condition.

type Payment =
    | {
        method: "card";
        cardNumber: string;
      }
    | {
        method: "upi";
        upiId: string;
      };
function processPayment(payment: Payment) {
    if (payment.method === "card") {
        console.log(payment.cardNumber);
    }
    if (payment.method === "upi") {
        console.log(payment.upiId);
    }
}

Here, method is the discriminant.

  • For method: "card", TypeScript allows access to cardNumber.
  • For method: "upi", TypeScript allows access to upiId.

6. Practical React Example: Input Component

Consider a reusable Input component that supports two modes:

  • Text input: Accepts a string value.
  • Number input: Accepts a numeric value.

We can use a discriminated union to enforce the correct value and callback types.

Implementation:
import { ChangeEvent } from "react";
type InputProps =
    | {
        type: "text";
        value: string;
        onChange: (value: string) => void;
      }
    | {
        type: "number";
        value: number;
        onChange: (value: number) => void;
      };
function Input(props: InputProps) {
    if (props.type === "text") {
        return (
            <input
                type="text"
                value={props.value}
                onChange={(event: ChangeEvent<HTMLInputElement>) =>
                    props.onChange(event.target.value)
                }
            />
        );
    }
    return (
        <input
            type="number"
            value={props.value}
            onChange={(event: ChangeEvent<HTMLInputElement>) =>
                props.onChange(Number(event.target.value))
            }
        />
    );
}
Usage:
<Input
    type="text"
    value="John"
    onChange={(value) => console.log(value.toUpperCase())}
/>
<Input
    type="number"
    value={100}
    onChange={(value) => console.log(value.toFixed(2))}
/>

The callback parameter is automatically inferred as string or number, depending on the selected input mode.

Important: HTML number inputs still expose their value as a string through the DOM event. The component converts it to a number using Number(). In a real form, also handle empty or invalid input values according to your validation requirements.

7. Practical React Example: Loading, Success and Error States

Discriminated unions are particularly useful for managing API request states.

Instead of maintaining separate state variables that can accidentally represent contradictory conditions, define one state type.

Without a discriminated union:
interface UserState {
    loading: boolean;
    data?: User[];
    error?: string;
}

This allows confusing combinations, such as loading being true while an error is also present.

Better approach:
interface User {
    id: number;
    name: string;
}
type UserState =
    | {
        status: "loading";
      }
    | {
        status: "success";
        data: User[];
      }
    | {
        status: "error";
        error: string;
      };

Now each state has its own required properties.

React component:
function UserList({ state }: { state: UserState }) {
    switch (state.status) {
        case "loading":
            return <p>Loading users...</p>;
        case "error":
            return <p>Error: {state.error}</p>;
        case "success":
            return (
                <ul>
                    {state.data.map(user => (
                        <li key={user.id}>
                            {user.name}
                        </li>
                    ))}
                </ul>
            );
        default:
            return assertNever(state);
    }
}
function assertNever(value: never): never {
    throw new Error("Unexpected state");
}

The never type helps identify missing cases when new states are added to the union.

8. Practical React Example: Different Card Variations

Suppose an application has different card types:

  • Product card
  • Profile card
  • Notification card

Each card requires different properties.

Define the types:
type CardProps =
    | {
        variant: "product";
        name: string;
        price: number;
      }
    | {
        variant: "profile";
        name: string;
        role: string;
      }
    | {
        variant: "notification";
        message: string;
        date: string;
      };
Implement the component:
function Card(props: CardProps) {
    switch (props.variant) {
        case "product":
            return (
                <div>
                    <h3>{props.name}</h3>
                    <p>Price: {props.price}</p>
                </div>
            );
        case "profile":
            return (
                <div>
                    <h3>{props.name}</h3>
                    <p>Role: {props.role}</p>
                </div>
            );
        case "notification":
            return (
                <div>
                    <p>{props.message}</p>
                    <small>{props.date}</small>
                </div>
            );
        default:
            return assertNever(props);
    }
}
Usage:
<Card
    variant="product"
    name="Laptop"
    price={50000}
/>
<Card
    variant="profile"
    name="John"
    role="Developer"
/>
<Card
    variant="notification"
    message="New message received"
    date="02 November 2026"
/>

Each card variation receives only the properties relevant to that variation.

9. Discriminated Unions vs Optional Props

Feature Optional Props Discriminated Unions
Property requirements Properties may be optional independently. Each variation defines its required properties.
Type safety Can allow invalid combinations. Prevents many invalid combinations.
Type narrowing May require additional checks. Uses the discriminant to narrow the type.
Maintainability Can become difficult with many variations. Clearly separates each variation.
Best use Truly optional, independent properties. Props that depend on a selected mode or variant.

10. Best Practices

  1. Use a clear discriminant: Prefer names such as type, variant, status or mode.
  2. Use literal values: Values such as "link", "action" and "loading" make variations explicit.
  3. Keep each variation focused: Define only the properties required by that variation.
  4. Use switch statements: They make multiple variations easier to understand.
  5. Use exhaustive checking: Use a never helper to catch missing cases.
  6. Avoid unnecessary optional properties: Do not make required properties optional just to support multiple component modes.
  7. Extract complex types: Keep large component prop definitions in separate type declarations.

11. Common Mistakes

  • Using optional properties for mutually exclusive component modes.
  • Using a regular string instead of specific literal types for the discriminant.
  • Accessing variation-specific properties before narrowing the type.
  • Forgetting to handle a newly added variation in a switch statement.
  • Creating too many variations when a simpler component design would be clearer.
  • Assuming TypeScript types validate external API data at runtime.

12. When Should You Use Discriminated Unions?

Use discriminated unions when a React component has different modes and each mode requires a different set of properties.

Common scenarios:
  • Button components with link and action modes.
  • Input components with text, number and date modes.
  • Cards with product, profile and notification variations.
  • API request states such as loading, success and error.
  • Payment components with card, UPI and other payment methods.
  • Form fields with different validation or value types.
  • Modal components with confirmation and information modes.

13. Interview Questions and Answers

Q1. What is a discriminated union in TypeScript?

A discriminated union is a union of multiple object types that share a common property with different literal values. TypeScript uses that property to identify and narrow the active type.

Q2. What is a discriminant property?

It is the common property that identifies which variation of a union is being used. Examples include type, status and variant.

Q3. Why are discriminated unions useful in React?

They help create reusable components with different modes while ensuring that each mode receives the correct required properties.

Q4. How are discriminated unions different from optional props?

Optional props allow properties to be independently omitted, which can permit invalid combinations. Discriminated unions define separate valid combinations and enforce their required properties.

Q5. What is type narrowing?

Type narrowing is the process of reducing a union type to a specific type using conditions such as if, switch or other type guards.

Q6. What is the purpose of the never type?

It represents values that should not occur. In exhaustive switch statements, it helps TypeScript detect when a union variation has not been handled.

Q7. Can discriminated unions be used with React state?

Yes. They are useful for representing mutually exclusive states such as loading, success and error, ensuring that each state has the appropriate properties.

14. Key Takeaways

  • Discriminated unions represent multiple valid object shapes using a shared property.
  • The discriminant identifies the active variation.
  • They prevent many invalid combinations of React component props.
  • TypeScript automatically narrows the type based on the discriminant.
  • They are especially useful for reusable components, forms, cards and API states.
  • Use never for exhaustive checking when handling all union variations.

Golden Rule: When a React component has different modes with different required properties, use discriminated unions instead of making every property optional. This produces cleaner component APIs and stronger compile-time type safety.

🔙
How to Avoid any in React Applications :👈 👉:Common TypeScript Errors in React

Comments and Discussion