You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This should ideally produce a type error, because:
as="button" → the ref should be HTMLButtonElement
but the user passed HTMLAnchorElement
However, since Headless UI uses Ref<HTMLElement>, the incorrect ref type is allowed.
Because Headless UI encourages polymorphism (as="button", as="a", custom components, and Fragment), I would like to propose an approach that enables strict ref inference only when as is a semantic HTML tag, without breaking the flexibility Headless UI currently provides.
Proposed solution
My suggestion is to enhance this by adding TTag and conditionally enforcing strict ref types only when the tag is a semantic HTML element:
exporttypeRefProp<TextendsFunction,TTagextendsElementType=any,>=// If TTag is an intrinsic HTML element, infer the correct ref typeTTagextendskeyofJSX.IntrinsicElements
? {ref?: Ref<JSX.IntrinsicElements[TTag]extendsReact.DetailedHTMLProps<React.HTMLAttributes<infer TElement>,any>
? TElement
: never>}
: // Otherwise, fall back to Headless UI's existing behaviorTextends(props: any,ref: Ref<infer RefType>)=>any
? {ref?: Ref<RefType>}
: never;
Then apply the updated RefProp in each component’s internal typing—for example, for Button:
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
What package within Headless UI are you using?
@headlessui/react
What version of that package are you using?
v2.2.9
What browser are you using?
Chrome
Describe your issue
Headless UI components currently accept refs using a broad type signature like:
This works, but it does not provide strict ref type validation when the as prop is set to a specific HTML tag.
This should ideally produce a type error, because:
However, since Headless UI uses
Ref<HTMLElement>, the incorrect ref type is allowed.Because Headless UI encourages polymorphism (as="button", as="a", custom components, and Fragment), I would like to propose an approach that enables strict ref inference only when as is a semantic HTML tag, without breaking the flexibility Headless UI currently provides.
Proposed solution
My suggestion is to enhance this by adding TTag and conditionally enforcing strict ref types only when the tag is a semantic HTML element:
Then apply the updated RefProp in each component’s internal typing—for example, for Button:
Example outcome
If you'd like, I can help you write a clean PR description too.
Beta Was this translation helpful? Give feedback.
All reactions