Skip to content

QuizNot attempted

Polymorphic 'as' prop

Which of these JSX lines are type errors?
type TextProps<E extends React.ElementType> = { as?: E; size?: 'sm' | 'md' | 'lg' } &
Omit<React.ComponentProps<E>, 'as' | 'size'>;
function Text<E extends React.ElementType = 'span'>({ as, ...rest }: TextProps<E>) { /* … */ }
<Text as="label" htmlFor="name">Name</Text> // (1)
<Text as="p1">Hello</Text> // (2)
<Text as="label" href="/home">Home</Text> // (3)
<Text as="a" href="/home" size="md">Home</Text> // (4)

Select all that apply.

1–4 to choose, Enter to submit
Show answer & explanation

Correct answers:

  • (2)
  • (3)
  • E is inferred from as, then ComponentProps<E> supplies exactly that element's props: (2) fails because 'p1' is not a key of JSX.IntrinsicElements (so it breaks the E extends ElementType constraint), and (3) fails because href is not a label prop.
  • Not (1): htmlFor is a valid label prop.
  • Not (4): href is an anchor prop and size comes from the own props, which Omit keeps from clashing with any native size.