Search⌘ K
AI Features

Handling Default Values for the Polymorphic Prop

Understand how to handle default values for the polymorphic 'as' prop in React components using TypeScript. Learn to properly assign default types so TypeScript enforces valid HTML attributes, preventing incorrect usage like assigning an href to a span. This lesson ensures your polymorphic components are both flexible and type-safe.

Let's consider our current solution, and pay attention to where a default element is provided if the as prop is omitted.

TypeScript 3.3.4
type PolymorphicTextProps<C extends React.ElementType> = {
as?: C;
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;
export const PolymorphicText = <C extends React.ElementType>({
as,
children,
...restProps
}: PolymorphicTextProps<C>) => {
const Component = as || "span";
return <Component {...restProps}>{children}</Component>;
};

Let's look at line 11 above. If the as prop is not provided, it will default to the string span. ...