Skip to content

Bug: Polymorphic Types #2120

@scurker

Description

@scurker

Polymorphic components in Cauldron are not correctly validating TypeScript types. Invalid props are not being caught by TypeScript, and valid props for polymorphic elements are incorrectly showing errors when we remove the cast.

Steps to reproduce

Some of the polymorphic types seem to not be validating properties correctly, some examples:

// This should error, because `foo="bar"` is not a valid property for this component
<ActionListItem foo="bar" />

Removing the as PolymorphicComponent<Props> cast fixes prop validation but breaks the polymorphic functionality entirely:

// This SHOULD be valid but shows error, "href" is valid for anchor elements
<ActionListItem as="a" href="/example" />

// This SHOULD be valid but shows error, button props should be allowed
<ActionListItem as="button" type="submit" />

We should investigate to see why types aren't propagating through correctly and fix it.

Expected Behavior

  • TypeScript should error when invalid props are passed to components
  • TypeScript should allow valid props for the element type specified in the as prop
  • Type inference should work correctly for both the base component and polymorphic variants

The issue appears to be in the PolymorphicComponent type definition where the intersection and merging of types is not working as expected. The current implementation:

export type PolymorphicComponent
  Props = {},
  ElementType extends React.ElementType = React.ElementType
> = Merge
  React.ForwardRefExoticComponent<Props>,
  {
    <T extends React.ElementType = ElementType>(
      props: PolymorphicComponentProps<Props, T>
    ): React.ReactElement | null;
  }
>;

We will need to check all of the different polymophic components to ensure types work for the different types, validating the intrinsic props as well as the polymorphic component type.

Version

v4.6.x

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions