Polymorphic React Components with an as Prop in TypeScript
Type a Button or Box that renders as a, button or a router Link, with the right props for each element and a correctly typed ref.
In this chapter
Polymorphic components with an as prop
More on Patterns from open source
Keep learning
Overview
chapters · patterns from open source Polymorphic components with an as prop One Button that can render a button, a link or a router Link, and gets the right props for each.
1. The problem: an as prop with loose props
The as prop picks which HTML element (or component) the Button renders, e.g. as="a" for a link. The quick version types as as any element. It lets every other prop be any (the "anything goes" type, with no checks). So typos are never caught.
Button.tsx: the index signature swallows everything
type Props size: ("sm" | "lg") & number → never Type 'string' is not assignable to type 'undefined'. ComponentPropsWithoutRef + Omit Omit removes <input>'s own size first, so only our "sm" | "lg" is left. Our keys win. Refs are handled separately (React 19 passes ref as a normal prop). C extends ElementType Any tag name ("a", "li") or component. = "button" default What C is when no as prop is given. Inside Button, C is still unknown, so TypeScript cannot match rest to its props and reports an error. Giving Comp the broad type ElementType turns that check off in this one spot. Why size: "sm" fails without Omit our props say size?: "sm" | "lg" <input> props say size?: number & keeps both rules at once size?: ("sm" | "lg") & number no value is a word and a number
5. How component libraries do it
Same goal, different APIs prop name props follow the element Chakra UI generic over the element type an overridable-component type maps component → props a polymorphic factory helper Radix UI Slot merges props onto the child element instead as / component prop asChild (Radix Slot) <Button asChild>Cart</Button>. The child is typed by its own JSX, so no generic magic.
Remember
An index signature of any turns off prop checking. Make the element a generic: C extends React.ElementType. Give C a default so a bare Button is a button. Inside, widen to ElementType once and spread. Radix avoids the generic with asChild. ! Cheat code Generic C from as. Borrow ComponentPropsWithoutRef<C>. Omit your own keys so yours win. → Go deeper: generic React components and hooks, Partial, Pick, Omit…, constraints and defaults, slow types.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.