kripod / kripod/react-polymorphic-types

Typing a `createHeading('h1')` function

Open
#6 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
197
Forks
9
PR merge metrics
No merged PRs in 30d

Description

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](https://github.com/rafgraph/react-interactive#using-createinteractive), and [code](https://github.com/rafgraph/react-interactive/blob/main/src/index.tsx#L814-L866).
```js
const StyledInteractiveButton = styled(createInteractive('button'), { color: 'green' });
// OR

```

---

Building off of your `` example in the readme I have the following, which works but only because I'm using `any`. Also see [this codesandbox](https://codesandbox.io/s/polymorphic-types-createheading-gdvz6?file=/src/App.tsx) which has the below code along with a few other attempts. Thanks!
```ts
function createHeadingWithRef<
T extends React.ElementType = typeof HeadingDefaultElement
>(as: T): React.ForwardRefExoticComponent, "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,
ref: React.ForwardedRef
) {
return ;
});
return WrappedHeading;
}
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the repository README’s example and compare it with the linked React Interactive createInteractive implementation in src/index.tsx. Investigate how createHeading('h1') can preserve ref forwarding and a predefined as prop without any. Done means the returned component is fully typed for the described polymorphic and CSS-in-JS usages.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.