← Back to React, page 5

react-0084 · Hard senior

How do you build a type-safe polymorphic component with an "as" prop in TypeScript, and what are its limits?

Make the component generic over the element type: T extends ElementType = 'span', accept as?: T, and combine the component's own props with Omit<ComponentPropsWithoutRef<T>, keyof OwnProps>. Then as="a" accepts href, as="button" accepts onClick and type, and a mismatch such as href on a span is a compile error. Limits are heavy types, slower editor feedback and awkward ref typing, so some design systems prefer asChild composition.

Full answer

Design system components such as Text, Box or Button often need to render different elements: a button that is really a link, or a heading with the style of a paragraph. A polymorphic as prop does this. Plain JavaScript is easy. Type safety is the hard part.

The type has three pieces. T extends ElementType = 'span' is a type parameter naming the element or component to render (ElementType covers tag names and components). The component's own props, such as tone and children, are declared in OwnProps<T> along with as?: T. The rest of the props come from the target element: Omit<ComponentPropsWithoutRef<T>, keyof OwnProps<T>>. Omitting the own keys prevents conflicts, where for example your tone collides with a native attribute.

When TypeScript sees <Text as="a" href="/courses">, it infers T as "a" and allows anchor attributes. With as="span", href is rejected, and a misspelled attribute is rejected too. This was checked with the compiler for the example below.

Implementation detail: inside the component, assign const Component: ElementType = as ?? 'span'. Widening to ElementType avoids a type explosion in the JSX expression, at the cost of one internal loose type that the public signature protects.

Refs: in React 19, ref is a prop, so use ComponentPropsWithRef<T> if you need it. With forwardRef, generics need a cast, which is why older polymorphic types were awkward.

Limits. The types are long and can slow the editor. Error messages are hard to read. Component targets with required props need care. Many teams prefer composition with an asChild prop (Radix UI Slot): the component clones its single child and merges props, which is easier to type and covers links in routers. Choose by team preference and keep the surface small.

Accessibility also matters: changing the element changes semantics. A div with an onClick is not a button, so document which elements are allowed.

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

type TextOwnProps<T extends ElementType> = {
  as?: T;
  tone?: 'plain' | 'muted';
  children: ReactNode;
};

type TextProps<T extends ElementType> = TextOwnProps<T> & Omit<ComponentPropsWithoutRef<T>, keyof TextOwnProps<T>>;

function Text<T extends ElementType = 'span'>({ as, tone = 'plain', children, ...rest }: TextProps<T>) {
  const Component: ElementType = as ?? 'span';
  return (
    <Component data-tone={tone} {...rest}>
      {children}
    </Component>
  );
}

export default function App() {
  return (
    <div>
      <Text>Plain span</Text>
      <Text as="a" href="/courses" tone="muted">
        Courses
      </Text>
      <Text as="button" type="button" onClick={() => console.log('pressed')}>
        Press
      </Text>
    </div>
  );
}

The file passed the strict TypeScript check. In a separate check, <Text as="span" href="/x"> and a misspelled attribute on an anchor were both rejected by the compiler, as the answer says. Rendered result: <div><span data-tone="plain">Plain span</span><a data-tone="muted" href="/courses">Courses</a><button data-tone="plain" type="button">Press</button></div>

Key points

  • Make the component generic over T extends ElementType with a default element.
  • Combine own props with Omit<ComponentPropsWithoutRef<T>, keyof OwnProps>.
  • TypeScript then checks element-specific props from the as value.
  • Widen to ElementType inside the implementation, and keep the public type strict.
  • Consider asChild composition when polymorphic types become too heavy, and keep semantics accessible.

Common mistakes

  • Typing the rest props as any, which removes all checking.
  • Forgetting to omit the own prop keys, so the types conflict.
  • Allowing as="div" for a clickable control and losing keyboard and screen reader behaviour.
  • Making the type so complex that the editor becomes slow.
  • Ignoring ref typing and breaking forwarded refs.

Follow-ups

  • How does the asChild pattern in Radix UI differ from an as prop?
  • How do you type the ref for a polymorphic component in React 19?
  • How would you restrict as to a small set of elements?

Tips

  • Show the three-part type. It is the whole answer.
  • Mention accessibility. Elements carry semantics.
  • Offer asChild as the alternative and compare them briefly.