MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Polymorphic Component Typing with As and ComponentPropsWithoutRef0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
9.1Typing Functional Components and Props in TypeScript9.2Typing React Hooks, Generics, and Refs9.3Typing Synthetic Events and Form Elements9.4Polymorphic Component Typing with As and ComponentPropsWithoutRef
HomeTutorialsReact.js for AdvancedPolymorphic Component Typing with As and ComponentPropsWithoutRef
JWT Authentication Flow and Silent Token Refresh

Polymorphic Component Typing with As and ComponentPropsWithoutRef

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

A polymorphic component is an advanced design system component that can dynamically change its underlying HTML element or React component via an as prop while retaining strict TypeScript type safety. For example, a <Button as="a" href="/login"> renders an <a> tag and permits href, while <Button as="button" type="submit"> forbids href and permits type.


1. The Challenge of Polymorphic Components

Without polymorphism, design system developers often duplicate code: creating <Button>, <LinkButton>, <DivButton>.

Naive typing using React.ElementType fails because TypeScript cannot dynamically validate that an href prop is only legal when as="a", or that target is illegal when as="button".


2. Constructing the Polymorphic Type Helper

1import React, { ComponentPropsWithoutRef, ElementType, ReactNode } from "react";
2 
3// 1. As prop definition
4type AsProp<C extends ElementType> = {
5 as?: C;
6};
7 
8// 2. Props to omit from the underlying element to prevent conflicts
9type PropsToOmit<C extends ElementType, P> = keyof (AsProp<C> & P);
10 
11// 3. Polymorphic component prop type combining custom props with element attributes
12export type PolymorphicComponentProps<
13 C extends ElementType,
14 Props = {}
15> = Props &
16 AsProp<C> &
17 Omit<ComponentPropsWithoutRef<C>, PropsToOmit<C, Props>>;

3. Implementing a Polymorphic <Button> Component

1import React, { ElementType } from "react";
2import { PolymorphicComponentProps } from "./types";
3 
4interface ButtonCustomProps {
5 variant?: "solid" | "outline" | "ghost";
6 size?: "sm" | "md" | "lg";
7 children?: React.ReactNode;
8}
9 
10// Default element when 'as' is omitted is "button"
11type ButtonProps<C extends ElementType = "button"> = PolymorphicComponentProps<
12 C,
13 ButtonCustomProps
14>;
15 
16export function Button<C extends ElementType = "button">({
17 as,
18 variant = "solid",
19 size = "md",
20 children,
21 className = "",
22 ...restProps
23}: ButtonProps<C>) {
24 // Determine the dynamic component or tag
25 const Component = as || "button";
26 
27 const baseStyles = "inline-flex items-center justify-center font-semibold rounded-lg transition";
28 const sizeStyles = {
29 sm: "px-3 py-1.5 text-xs",
30 md: "px-4 py-2 text-sm",
31 lg: "px-6 py-3 text-base",
32 };
33 const variantStyles = {
34 solid: "bg-cyan-600 hover:bg-cyan-500 text-white",
35 outline: "border border-cyan-500 text-cyan-400 hover:bg-cyan-500/10",
36 ghost: "text-slate-300 hover:bg-slate-800",
37 };
38 
39 const combinedClass = `${baseStyles} ${sizeStyles[size]} ${variantStyles[variant]} ${className}`;
40 
41 return (
42 <Component className={combinedClass} {...restProps}>
43 {children}
44 </Component>
45 );
46}

4. Compile-Time Type Safety in Action

1// ✅ 1. Standard button: accepts type="submit", disabled
2<Button variant="solid" type="submit">
3 Submit Form
4</Button>
5 
6// ✅ 2. Rendered as anchor: accepts href, target="_blank", rel
7<Button as="a" href="https://example.com" target="_blank">
8 Visit Documentation
9</Button>
10 
11// ✅ 3. Rendered as React Router Link: accepts to="/dashboard"
12import { Link } from "react-router-dom";
13<Button as={Link} to="/dashboard">
14 Go to Dashboard
15</Button>
16 
17// ❌ 4. COMPILE ERROR: type="submit" is illegal on an anchor tag!
18// <Button as="a" href="/profile" type="submit">Invalid</Button>

5. Adding ref Support with Polymorphic forwardRef

To forward refs safely across polymorphic elements:

1export type PolymorphicRef<C extends React.ElementType> =
2 React.ComponentPropsWithRef<C>["ref"];

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the defining capability of a polymorphic React component?
Question 2
Why is ComponentPropsWithoutRef<C> used instead of ComponentProps<C>?
Question 3
In the polymorphic Button component, what happens if a developer passes href="https://google.com" without specifying as="a"?
Question 4
Why is Omit<ComponentPropsWithoutRef<C>, PropsToOmit<C, Props>> used in the polymorphic helper?
Question 5
Can a polymorphic component accept another React component (like React Router Link) into its as prop?
Next Lesson

JWT Authentication Flow and Silent Token Refresh

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Typing Synthetic Events and Form ElementsJWT Authentication Flow and Silent Token Refresh

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext