Skip to content

Lesson 6 of 9 · 26m

Polymorphic Components and the `as` Prop

Type components that can render as a button, link, or custom element while preserving the target element's props.

Polymorphic components are where TypeScript earns its keep and where many teams decide type safety is not worth it. A Button that can render as an <a> for links, a <button> for actions, or a router Link is wonderful product design and a genuinely hard typing problem.

The runtime pattern is simple

function Button({ as: Component = "button", className, ...props }) {
  return <Component className={`btn ${className ?? ""}`} {...props} />;
}

The type problem is that valid props depend on as. An href is valid for a, invalid for button; type="submit" is valid for button, nonsense for a.

A practical typed version

type ButtonOwnProps = {
  variant?: "primary" | "secondary" | "danger";
};
type ButtonProps<C extends React.ElementType> = ButtonOwnProps & {
  as?: C;
} & Omit<React.ComponentPropsWithoutRef<C>, keyof ButtonOwnProps | "as">;
function Button<C extends React.ElementType = "button">(props: ButtonProps<C>) {
  const { as: Component = "button", variant = "primary", ...rest } = props;
  return <Component className={`btn btn-${variant}`} {...rest} />;
}

Now usage is checked against the rendered element:

<Button type="submit">Save</Button>
<Button as="a" href="/settings">Settings</Button>
// <Button href="/x">Nope</Button> // correctly rejected for default button

Ref forwarding changes the type again

If the component must forward refs, use a helper type or interface carefully. React.ElementRef<C> or ComponentPropsWithRef<C> enters the picture, and the implementation often needs a deliberate cast at the boundary. This is acceptable when the public type is precise and the internal unsafe surface is tiny.

const Button = forwardRef(function Button<C extends React.ElementType = "button">(
  props: ButtonProps<C>,
  ref: React.Ref<Element>,
) {
  // implementation
}) as <C extends React.ElementType = "button">(
  props: ButtonProps<C> & { ref?: React.ComponentPropsWithRef<C>["ref"] },
) => React.ReactElement | null;

The cast is ugly. The alternative — giving consumers any — is worse. Put the complexity behind a tested boundary.

When not to do it

If only two cases exist, separate components or a small union API may be simpler:

<ActionButton onClick={save}>Save</ActionButton>
<ActionLink href="/settings">Settings</ActionLink>

Polymorphism is for design-system primitives with real reuse, not for proving TypeScript can bend.

Field notes

  • Test invalid usage with @ts-expect-error; otherwise a refactor can silently widen the API.
  • Keep own prop names (variant, size) out of collisions with host props.
  • Router links are the reason this pattern exists; verify them before shipping the abstraction.
  • If autocomplete is unreadable in your editor, simplify before cleverness spreads.

Was this lesson helpful?

Sign in to rate