Senior LevelReact JS & React 19
How do you build type-safe polymorphic components (<Box as="a" href="...">) in TypeScript?
❓ Interview Prompt: Explain Polymorphic Components (`as` prop), TypeScript generics, `ComponentPropsWithoutRef`, and type-safe dynamic element rendering.
A Polymorphic Component allows rendering different underlying HTML tags or React components using an 'as' prop while strictly enforcing matching TypeScript props:
TypeScript Generic Pattern:
'type BoxProps<E extends React.ElementType> = { as?: E } & React.ComponentPropsWithoutRef<E>;'
•
Passing 'as="a"' enforces 'href' prop requirement; passing 'as="button"' enforces 'onClick' prop!
Code Implementation Example
tsx
import React from 'react';
type BoxProps<E extends React.ElementType> = {
as?: E;
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<E>;
export function Box<E extends React.ElementType = 'div'>({ as, children, ...props }: BoxProps<E>) {
const Component = as || 'div';
return <Component {...props}>{children}</Component>;
}
// Usage:
<Box as="a" href="https://example.com">Link</Box>; // Valid!
// <Box as="button" href="#">Error!</Box>; // TS Error: 'href' does not exist on button!💡Building a polymorphic component with TypeScript generic props.
🎯 Interview Key Takeaway
Use TypeScript generics with ComponentPropsWithoutRef to build type-safe polymorphic components with the 'as' prop.
#Polymorphic#TypeScript#Design System#Senior
Back to all React JS & React 19 Questions→