Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typing a createHeading('h1') function #6

Open
rafgraph opened this issue Apr 30, 2021 · 0 comments
Open

Typing a createHeading('h1') function #6

rafgraph opened this issue Apr 30, 2021 · 0 comments

Comments

@rafgraph
Copy link

rafgraph commented Apr 30, 2021

Hi, I'm trying to type a create function that returns a fully typed component with ref forwarding and the as prop predefined.

This is needed when using a polymorphic component with CSS-in-JS libraries and other polymorphic components. I'm currently using a createInteractive function in React Interactive, see readme docs, and code.

const StyledInteractiveButton = styled(createInteractive('button'), { color: 'green' });
// OR
<SomePolymorphicComponent as={createInteractive('button')} />

Building off of your <Heading> example in the readme I have the following, which works but only because I'm using any. Also see this codesandbox which has the below code along with a few other attempts. Thanks!

function createHeadingWithRef<
  T extends React.ElementType = typeof HeadingDefaultElement
>(as: T): React.ForwardRefExoticComponent<Omit<HeadingProps<T>, "as">> {
  // without any get TS error on return type of WrappedHeading
  const WrappedHeading: any = React.forwardRef(function <
    T extends React.ElementType = typeof as
  >(
    props: PolymorphicPropsWithoutRef<HeadingOwnProps, T>,
    ref: React.ForwardedRef<Element>
  ) {
    return <Heading {...props} as={as} ref={ref} />;
  });
  return WrappedHeading;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant