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
{{ message }}
Repository navigation
[labs/react] export component and prop types #3188
Currently we rely on Typescript to infer what is returned from createComponent and although TS is fairly good, an inference is not as durable as an explicit typing.
This would be amazing for the Lit team's help on this kind of thing!
I started off on this typing journey just trying to give my component consumers some intellisense in their Typescript/React apps when they were consuming/using the components I build. I started with the typing suggested in this article:
and have since discovered and been troubleshooting some issues.
The things I've been going after for the "bulletproof" web component type in react are:
enable all the common react syntax props correctly on web component tags
so all of the following wouldn't give type errors:
<x-comp style={{}} >
<x-comp ref={} >
<x-comp onChange={} >
potentially exclude className for styling since class is the proper way to style custom elements even in react
type custom events with the on${name} syntax
add support for typing the web component's own properties
correctly type children using react's typing so that children can be other react nodes, other web components, HTMLCollections, and strings, etc
The following is our current working "bulletproof" web component type. It does not yet have custom event notation working, but I believe the technique mentioned in Cory's article above could be applied.
HTMLAttributes<ComponentClass> - enables all the react syntax
Omit<Partial<ComponentClass>, 'children'> - enables all the properties from the component, but omit's children so that react's definition of children from HTMLAttributes
{ref?: MutableRefObject<ComponentClass | undefined>} - adds the ref={} syntax typing and types the ref as the component if defined, or undefined if not
I'm sure there's a cleaner way to exercise all the parts, and I'm sure there's a cleaner/more modern mechanism for this "bulletproof" type, and Id love if this package explores those options with the Lit team's expertise and provided this type back out for us component devs to use!
I've been currently working on a PR to export an explicit typing from our createComponent function that is very close to what @michaelwarren1106 has described.
exporttypeUserProps<I,EextendsEvents={}>=Partial<ReactProps<I,E>&ElementWithoutPropsOrEvents<I,E>&EventProps<E>>;// Props used by this component wrapper. This is the UserProps and the// special `__forwardedRef` property. Note, this ref is special because// it's both needed in this component to get access to the rendered element// and must fulfill any ref passed by the user.typeComponentProps<I,EextendsEvents={}>=UserProps<I,E>&{__forwardedRef?: React.Ref<I>;};exporttypeWrappedWebComponent<I,EextendsEvents={}>=React.ForwardRefExoticComponent<React.PropsWithoutRef<UserProps<I,E>>&React.RefAttributes<I>>;
In the above WrappedWebComponent is the return type of createComponent but there's no reason we couldn't also export UserProps as a kind of IntrinsicElement.
There would be caveats like event listners might be correctly typed but react might not handle adding and removing them (this is where the lit-labs react package helps)
A type that does not include event listeners would be a good place to start. That is the main difference between React handling web components and LitLabs React Wrapper handling web components.
this leads me to believe that any type for react we create would need to basically omit a list of props that are common to both react syntax and standard HTML props, so that the react typing can take over and be correct in the context of a react app.
amazing! I can definitely test this out some more.
One question I've had come up that i wanted to ask. Does this new type collection type the event.target correctly on the event listeners? That was another struggle that I'm not good enough at Typescript to solve haha.
So i tested the WebComponentProps type here and I found one error, and had one question.
The error is that class isn't accounted for. When using a web component as a web component in a react app, you can't use className, only class will work, right? So that needs to be reflected in the typing, and I don't see it currently.
The question is "Why can't the typing be attribute-based instead of property-based?" Right now, when we're seeing typing messages and autocomplete help bubbles in VSCode, they always contain the JS property names from my WC classes, but not the attribute names. But in react/JSX, only the attribute names work. So something like:
<some-web-component align
would show a typing hint like alignX or alignY instead of align-x and align-y. If the dev uses the autocomplete chooser, they'll get:
<some-web-component alignY=
and that wont work. A related note is that the type above didnt seem to provide any attribute value hinting when you get the correct attribute. If you type:
<some-web-component align-y="
you dont get any completion help for the values for alignY ('start', 'center', 'end' etc). Presumably thats because the JS prop and the HTML attribute have different names. IMO tho, the typing should reflect that somehow? Does that have to do with what is in HTMLElementTagMap?
"Why can't the typing be attribute-based instead of property-based?"
Would be curious to expand on that.
We set the "attributes" from react props as properties on the element. We also interrogate the element prototype to find which properties are apart of that element. This also lets us allow us to infer some kind of type from properties on the web component with TS.
I think if we did all our typing by "attributes" everything might be strings :)
that’s pretty true. my main use case i guess is with multi-word attributes like display-name. say in my WC, i have a reactive property displayName with an attribute name defined from the Lit decorator as display-name.
In JSX when using a WC tag, say I type the tag name and start typing some attribute <x-foo d. The intellisense would show me displayName:string; right? if I choose that from
the context menu, then i’d have <x-foo displayName=“” which wouldn’t be right? In JSX for WCs youve gotta use the actual attribute name, right?
So if the typing isn’t smart enough to know that in JSX displayName should be autocompleted as display-name, then won’t devs who choose to use the autocomplete have to go back and change the autocomplete back to display-name=?
you’re right that the attribute typing would all be strings and booleans, but that’s all JSX can set on a WC tag right now anyway, right? maybe once they land support for setting either/both attrs and props on a WC it’ll get better?
i wonder if it’s something to do with HTMLElementTagMap? I think Justin said somewhere on discord that JSX falls back to that for web component typing, so if that’s true, I wonder if there’s some like types generation helper function that could connect attrs and props together and spit out typed attributes for usage in HTMLElementTagMap?
I'll close this issue as the original goal of this issue was completed a while back with @lit-labs/react exporting ReactWebComponent type as the type of the return value of createComponent() and WebComponentProps type as a utility to be used for adding to JSX.IntrinsicElements.
The latter is not feature-full as it creates a type based on the custom element class's properties. It turns everything optional, and still exposes ReactiveElement lifecycle methods in code suggestion. It'll also only work for properties with string values and isn't smart enough to detect properties with different attribute names. Addressing all of this is not possible without intimate knowledge of the custom element, making assumptions about it, and/or adding additional dependency to the package which I don't think we're ready to tackle at the moment.
Activity
michaelwarren1106 commentedon Jul 29, 2022
This would be amazing for the Lit team's help on this kind of thing!
I started off on this typing journey just trying to give my component consumers some intellisense in their Typescript/React apps when they were consuming/using the components I build. I started with the typing suggested in this article:
https://coryrylan.com/blog/how-to-use-web-components-with-typescript-and-react
and have since discovered and been troubleshooting some issues.
The things I've been going after for the "bulletproof" web component type in react are:
<x-comp style={{}} ><x-comp ref={} ><x-comp onChange={} >classNamefor styling sinceclassis the proper way to style custom elements even in reacton${name}syntaxchildrenusing react's typing so thatchildrencan be other react nodes, other web components, HTMLCollections, and strings, etcThe following is our current working "bulletproof" web component type. It does not yet have custom event notation working, but I believe the technique mentioned in Cory's article above could be applied.
Explanation of the parts:
HTMLAttributes<ComponentClass>- enables all the react syntaxOmit<Partial<ComponentClass>, 'children'>- enables all the properties from the component, but omit'schildrenso that react's definition of children fromHTMLAttributes{ref?: MutableRefObject<ComponentClass | undefined>}- adds theref={}syntax typing and types the ref as the component if defined, orundefinedif notI'm sure there's a cleaner way to exercise all the parts, and I'm sure there's a cleaner/more modern mechanism for this "bulletproof" type, and Id love if this package explores those options with the Lit team's expertise and provided this type back out for us component devs to use!
michaelwarren1106 commentedon Jul 29, 2022
Additional attempt at adding in custom events (only custom additional ones, not overwriting or omitting from events provided by
DOMAttributes)taylor-vann commentedon Jul 29, 2022
I find this part pretty interesting:
We already do this in a similar manner:
I've been currently working on a PR to export an explicit typing from our
createComponentfunction that is very close to what @michaelwarren1106 has described.#3163
In the above
WrappedWebComponentis the return type ofcreateComponentbut there's no reason we couldn't also exportUserPropsas a kind ofIntrinsicElement.There would be caveats like event listners might be correctly typed but react might not handle adding and removing them (this is where the lit-labs react package helps)
taylor-vann commentedon Jul 29, 2022
A type that does not include event listeners would be a good place to start. That is the main difference between React handling web components and LitLabs React Wrapper handling web components.
michaelwarren1106 commentedon Aug 1, 2022
another test I did today adds omission of the
styleprop from the component class so that react's inline style typing can take over:michaelwarren1106 commentedon Aug 1, 2022
this leads me to believe that any type for react we create would need to basically omit a list of props that are common to both react syntax and standard HTML props, so that the react typing can take over and be correct in the context of a react app.
taylor-vann commentedon Aug 2, 2022
@michaelwarren1106 totally agree and that's actually our goal code-wise! It's nice to see a similar conclusion independent of ours :)
taylor-vann commentedon Sep 30, 2022
@michaelwarren1106 an explicitly exported type
ReactWebComponentis now exported from@lit-labs/react!We're halfway to the type you requested!
I believe one of the following types would be what you needed
https://github.com/lit/lit/blob/main/packages/labs/react/src/create-component.ts#L29-L49
Curious to hear more though now that we're making progress!
michaelwarren1106 commentedon Sep 30, 2022
amazing! I can definitely test this out some more.
One question I've had come up that i wanted to ask. Does this new type collection type the
event.targetcorrectly on the event listeners? That was another struggle that I'm not good enough at Typescript to solve haha.taylor-vann commentedon Sep 30, 2022
I can definitely find out :3
michaelwarren1106 commentedon Oct 4, 2022
So i tested the
WebComponentPropstype here and I found one error, and had one question.The error is that
classisn't accounted for. When using a web component as a web component in a react app, you can't useclassName, onlyclasswill work, right? So that needs to be reflected in the typing, and I don't see it currently.The question is "Why can't the typing be attribute-based instead of property-based?" Right now, when we're seeing typing messages and autocomplete help bubbles in VSCode, they always contain the JS property names from my WC classes, but not the attribute names. But in react/JSX, only the attribute names work. So something like:
would show a typing hint like
alignXoralignYinstead ofalign-xandalign-y. If the dev uses the autocomplete chooser, they'll get:and that wont work. A related note is that the type above didnt seem to provide any attribute value hinting when you get the correct attribute. If you type:
you dont get any completion help for the values for alignY ('start', 'center', 'end' etc). Presumably thats because the JS prop and the HTML attribute have different names. IMO tho, the typing should reflect that somehow? Does that have to do with what is in HTMLElementTagMap?
taylor-vann commentedon Nov 9, 2022
Hey @michaelwarren1106! There have been some updates. I think some of our tests match your use case.
We declare the web component in the
HTMLElmenetTagNameMapand theIntrinsicElementsnamespaces.https://github.com/lit/lit/blob/main/packages/labs/react/src/test/create-component_test.tsx#L20-L31
Later those props are applied to an unwrapped custom web component. The types match both the unwrapped and wrapped component.
https://github.com/lit/lit/blob/main/packages/labs/react/src/test/create-component_test.tsx#L122
TS understands the properties
x-foorequires.taylor-vann commentedon Nov 9, 2022
Would be curious to expand on that.
We set the "attributes" from react props as properties on the element. We also interrogate the element prototype to find which properties are apart of that element. This also lets us allow us to infer some kind of type from properties on the web component with TS.
I think if we did all our typing by "attributes" everything might be strings :)
Or maybe I'm misunderstanding?
michaelwarren1106 commentedon Nov 9, 2022
that’s pretty true. my main use case i guess is with multi-word attributes like
display-name. say in my WC, i have a reactive propertydisplayNamewith an attribute name defined from the Lit decorator asdisplay-name.In JSX when using a WC tag, say I type the tag name and start typing some attribute
<x-foo d. The intellisense would show medisplayName:string;right? if I choose that fromthe context menu, then i’d have
<x-foo displayName=“”which wouldn’t be right? In JSX for WCs youve gotta use the actual attribute name, right?So if the typing isn’t smart enough to know that in JSX
displayNameshould be autocompleted asdisplay-name, then won’t devs who choose to use the autocomplete have to go back and change the autocomplete back todisplay-name=?you’re right that the attribute typing would all be strings and booleans, but that’s all JSX can set on a WC tag right now anyway, right? maybe once they land support for setting either/both attrs and props on a WC it’ll get better?
taylor-vann commentedon Nov 9, 2022
Oh I see, yah the wrapped components property names could potentially be different than the actual property names: ie kabob vs camel case.
It's possible to correlate the attribute names you want to property names using some kind of map.
That might be a feature worth chasing
michaelwarren1106 commentedon Nov 9, 2022
i wonder if it’s something to do with HTMLElementTagMap? I think Justin said somewhere on discord that JSX falls back to that for web component typing, so if that’s true, I wonder if there’s some like types generation helper function that could connect attrs and props together and spit out typed attributes for usage in HTMLElementTagMap?
taylor-vann commentedon Nov 9, 2022
That'd be an interesting default! And worth looking into, will do
augustjk commentedon Aug 17, 2023
I'll close this issue as the original goal of this issue was completed a while back with
@lit-labs/reactexportingReactWebComponenttype as the type of the return value ofcreateComponent()andWebComponentPropstype as a utility to be used for adding toJSX.IntrinsicElements.The latter is not feature-full as it creates a type based on the custom element class's properties. It turns everything optional, and still exposes ReactiveElement lifecycle methods in code suggestion. It'll also only work for properties with string values and isn't smart enough to detect properties with different attribute names. Addressing all of this is not possible without intimate knowledge of the custom element, making assumptions about it, and/or adding additional dependency to the package which I don't think we're ready to tackle at the moment.