Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 86

Polymorphic Components with Discriminated Unions

Recommended resources

Hello! Welcome back to our module on Advanced Component and TypeScript Patterns.

In our last lesson, we mastered TypeScript utility types like Pick, Omit, and ComponentPropsWithoutRef. You learned how to borrow and adapt existing type definitions to create flexible and maintainable component props, following the DRY (Don't Repeat Yourself) principle for types.

Today, we'll leverage that knowledge to tackle one of the most powerful patterns in modern React development. Our goal is to implement discriminated unions in component props for building polymorphic components. This will allow us to create components that can adapt their very structure and accepted props based on their usage, all while maintaining perfect, compile-time type safety.

This lesson is divided into two main parts:

  1. First, we'll solidify the concept of discriminated unions as a general TypeScript pattern.
  2. Then, we'll apply this pattern to build polymorphic components in React, most notably using the common as prop pattern.

What are Discriminated Unions?

At its core, a discriminated union is a way to combine several different object types into one union, where a single, common property—the discriminant—allows TypeScript to figure out which specific type you're dealing with at any given moment. This enables powerful type-narrowing and makes your code safer and more predictable.

For a comprehensive explanation of this core TypeScript feature, please watch the following video. It expertly covers the "what" and "why" of discriminated unions and introduces the "exhaustive switch" pattern, a compile-time technique to ensure you've handled every possible case in the union.

TypeScript Exhaustive Switch: How discriminated unions make your job easier!

This video from Andrew Burgess provides a fantastic, ground-up explanation of discriminated unions in TypeScript.

Watch from the beginning to 08:49. Pay close attention to: How a literal property (table: 'users') acts as the discriminant. How TypeScript narrows the type of the options object inside the switch statement. The concept of the 'exhaustive switch' using never to ensure all cases are handled at compile time.

To reinforce this concept with a text-based example, you can also review the first section of the following article.

Advanced typescript for React developers - discriminated unions

This article by Nadia Makarevich on DeveloperWay introduces discriminated unions with a clear, practical example, showing how they simplify type-guard functions.

Read the section titled 'Discriminated unions - beginning'. Notice how adding a __typename property (the discriminant) cleans up the conditional logic significantly.


Applying Discriminated Unions to Component Props

Now, let's apply this powerful pattern to React components. A common use case is when a component's props should change based on the value of another prop. For example, a Select component might behave differently if it's a multi-select versus a single-select.

Imagine a prop isMulti: boolean.

  • If isMulti is false, the onChange callback should receive a single value: (value: T) => void.
  • If isMulti is true, the onChange callback should receive an array of values: (value: T[]) => void.

A naive union type like (value: T | T[]) => void would force the developer to add type checks inside the callback. Discriminated unions solve this elegantly.

This image shows a simple example with a Modal component, where the variant prop dictates whether a title prop is required.

Discriminated Unions in TypeScript for React Component Props
This code defines `ModalProps` as a union of two types. One has `variant: 'no-title'`, and the other has `variant: 'title'` and a required `title: string` property. The component logic can then safely access `props.title` only when `props.variant === 'title'`. This is a classic discriminated union in action.

For a more detailed, practical walkthrough, let's turn back to the DeveloperWay article. It demonstrates exactly how to refactor a GenericSelect component's props to use a discriminated union.

Advanced typescript for React developers - discriminated unions

This section of the article provides a perfect, real-world example of using discriminated unions to improve the developer experience of a React component.

Read the section 'Discriminated unions in components props'. Focus on how GenericSelectProps is transformed into a union of SingleSelectProps and MultiSelectProps, with isMulti acting as the discriminant.

The key insight is to define separate interfaces for each variant and then union them together. The discriminant (isMulti in this case) must have a literal type (true or false), not the general boolean type.

// Common props for both variants
type BaseSelectProps<TValue> = { /* ... */ };

// Props for the single-select variant
interface SingleSelectProps<TValue> extends BaseSelectProps<TValue> {
  isMulti: false; // The discriminant
  onChange: (value: TValue) => void;
}

// Props for the multi-select variant
interface MultiSelectProps<TValue> extends BaseSelectProps<TValue> {
  isMulti: true; // The discriminant
  onChange: (value: TValue[]) => void;
}

// The final props type is a union of the two variants
type SelectProps<TValue> = SingleSelectProps<TValue> | MultiSelectProps<TValue>;

export const GenericSelect = <TValue extends Base>(props: SelectProps<TValue>) => {
  // Now, if you check `props.isMulti`, TypeScript will correctly narrow the type of `props.onChange`.
  if (props.isMulti) {
    // props.onChange is (value: TValue[]) => void
  } else {
    // props.onChange is (value: TValue) => void
  }
};

Building Polymorphic Components with the as Prop

We can now take this concept to its ultimate conclusion: creating components that can render as different HTML elements. This is the polymorphic component pattern, commonly implemented with an as prop.

The goal is to create, for example, a <Text> component that can render a p tag, an h1, or a span, and critically, it should only accept props that are valid for the element it's rendering.

  • <Text as="a" href="/home"> should be valid.
  • <Text as="p" href="/home"> should be a type error.

This pattern is a powerful combination of generics, the utility types you learned in the last lesson (ComponentPropsWithoutRef, Omit), and the principle of discriminated unions.

The following video provides a clear, step-by-step guide to building a polymorphic component from scratch.

React TypeScript Tutorial - 24 - Polymorphic Components

This tutorial from Codevolution walks through the entire process of creating a polymorphic Text component.

Please watch the full video (00:00 - 09:29). It covers: The problem: The need for semantic HTML elements. Introducing the as prop and typing it with React.ElementType. Using generics (E extends React.ElementType), React.ComponentProps, and Omit to dynamically include props for the specified element while avoiding type collisions.

Let's break down the final type structure, which is the heart of this pattern. It combines everything you've learned.

import type { ComponentPropsWithoutRef, ElementType, ReactNode } from 'react';

// 1. Define the props that are unique to YOUR component.
type TextOwnProps<E extends ElementType> = {
  children: ReactNode;
  as?: E; // The 'as' prop, typed with the generic.
  color?: 'primary' | 'secondary';
};

// 2. Create the final props type.
// It combines your own props with the props of the element being rendered.
type TextProps<E extends ElementType> = TextOwnProps<E> &
  // Use Omit to prevent collisions between your props and the native element's props.
  Omit<ComponentPropsWithoutRef<E>, keyof TextOwnProps<E>>;

// 3. Define the component using a generic with a default type.
export const Text = <E extends ElementType = 'div'>({
  as,
  children,
  color,
  ...rest // `rest` now contains all valid props for the element E.
}: TextProps<E>) => {
  const Component = as || 'div';
  return (
    <Component className={`color-${color}`} {...rest}>
      {children}
    </Component>
  );
};

// --- Usage ---
// <Text as="h1" id="main-heading">Heading</Text> // `id` is valid for h1
// <Text as="a" href="/">Link</Text>             // `href` is valid for a
// <Text as="p" href="/">Error!</Text>           // `href` is not valid for p

This pattern is incredibly powerful for creating design systems. Components like Button, Text, Box, and Card are prime candidates for becoming polymorphic. For a deeper read and to see how to abstract this pattern for reusability, the article "Polymorphic Components and the as Prop" is an excellent resource. The implementation is slightly different but achieves the same result.

Test your understanding!

You are building a custom Button component. It should be polymorphic, defaulting to a <button> element. It also has a custom variant prop ('primary' | 'secondary').

Your task is to define the ButtonProps type using the polymorphic component pattern. You need to combine your custom variant prop with all the props of the element specified by the as prop.

import type { ComponentPropsWithoutRef, ElementType } from 'react';

// Your custom props
type ButtonOwnProps<E extends ElementType> = {
  as?: E;
  variant: 'primary' | 'secondary';
};

// How would you define ButtonProps?
type ButtonProps<E extends ElementType> = /* Your solution here */
Show answer

Here's the solution:

import type { ComponentPropsWithoutRef, ElementType } from 'react';

type ButtonOwnProps<E extends ElementType> = {
  as?: E;
  variant: 'primary' | 'secondary';
};

type ButtonProps<E extends ElementType> = ButtonOwnProps<E> &
  Omit<ComponentPropsWithoutRef<E>, keyof ButtonOwnProps<E>>;

// Example Component:
const Button = <E extends ElementType = 'button'>({
  as,
  variant,
  children,
  ...rest
}: ButtonProps<E>) => {
  const Component = as || 'button';
  const variantClass = `btn-${variant}`;

  return (
    <Component className={variantClass} {...rest}>
      {children}
    </Component>
  );
};

This structure ensures that if you render <Button as="a" variant="primary" />, TypeScript will correctly type-check for href within ...rest, and if you render <Button as="button" variant="secondary" />, it will check for type or disabled.


Conclusion

You've now explored two powerful, related patterns for creating highly flexible and type-safe components. These techniques are hallmarks of advanced React and TypeScript development, particularly in the context of creating reusable UI libraries and design systems.

Key Takeaways:

  • Discriminated Unions are a core TypeScript feature where a union of object types is "discriminated" by a common property with a literal type, enabling precise type narrowing.
  • This pattern is ideal for component props where one prop's value dictates the shape or types of other props (e.g., isMulti controlling the onChange signature).
  • Polymorphic Components, typically using an as prop, are an advanced application of these principles. They combine generics (<E extends ElementType>) and utility types (ComponentPropsWithoutRef, Omit) to create components that can render as different HTML elements while inheriting the correct props for each.

Preview of the Next Lesson:
We've made our components flexible in the data they accept and the props they are defined with. Next, we'll focus on separating a component's logic from its presentation entirely. You will learn how to build a headless component to separate logic from presentation for maximum reusability, a pattern that takes component composition and flexibility to the next level.