FlashcardNot attempted
Polymorphic component recipe
Recall it before you reveal
How do you type a polymorphic <Box as="a" href="…"> component?
Space to reveal
Show answer & explanation
Make the element a generic inferred from as, then merge your own props over that element's props:
type Props<E extends React.ElementType, Own> = Own & { as?: E } & Omit<React.ComponentPropsWithoutRef<E>, keyof Own | 'as'>;
function Box<E extends React.ElementType = 'div'>({ as, tone, ...rest }: Props<E, BoxOwnProps>) { const Tag: React.ElementType = as ?? 'div'; // TS can't relate the generic rest to E return <Tag data-tone={tone} {...rest} />;}Omit lets your own props replace clashing native ones; destructure them so they are not spread onto the DOM. Annotating Tag as ElementType is the usual escape hatch inside the body, while callers stay fully checked. In React 19, add ref by using ComponentProps<E> instead, since ref is a normal prop.