Skip to content

Typing required props for as #7

Description

@rafgraph

Hi, is it possible to type the props that as is required to accept? Without this it is easy to pass in an as prop that is not compatible with the polymorphic component. Thanks.

Using the heading example in the readme (also see this codesandbox for a live reproduction):

// Heading from readme:
function Heading<
  T extends React.ElementType = typeof HeadingDefaultElement
>({ as, color, style, ...restProps }: HeadingProps<T>) {
  const Element: React.ElementType = as || HeadingDefaultElement;
  return <Element style={{ color, ...style }} {...restProps} />;
}

const MyHeading: React.FC<{}> = ({ children }) => <h1>{children}</h1>;

function App() {
  return (
    <>
      <Heading as={MyHeading} color="green">
        This should result in a type error because MyHeading doesn't accept a style prop,
        but typescript thinks it's fine even though it doesn't work.
      </Heading>
      {/* this errors because MyHeading doesn't accept a style prop
        <MyHeading style={{ color: "green" }}>MyHeading</MyHeading>
      */}
    </>
  );
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions