Destructuring props on a styled component throws a type error on property "as"
See original GitHub issueCurrent behaviour:
Receive the following error when destructuring props onto an emotion/styled component.
Type '{ children: (ReactNode | Element)[]; accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean | undefined; ... 356 more ...; key?: Key | ... 1 more ... | undefined; }' is not assignable to type '{ theme?: Theme | undefined; as?: ElementType<any> | undefined; }'. Types of property 'as' are incompatible. Type 'string | undefined' is not assignable to type 'ElementType<any> | undefined'. Type 'string' is not assignable to type 'ElementType<any> | undefined'.
This occurs on any tag you destruct functional component props on. styled.<element>'s “as” property doesn’t correspond with React.HTMLProps<HTMLElement>'s “as” property (can also be HTMLButtonElement).
To reproduce: See Example Here.
- Create a new functional component.
- Within functional component, add an emotion styled component.
- Add some arbitrary properties (for example elementHeight, doesn’t really matter) to the React.FC<Props> Props interface.
- Make sure to extend the React element of whatever HTML element you wish to destruct default properties on.
- destruct props ({…props}) on the intended HTML element
Expected behaviour:
- type of “as” corresponds with the React HTMLElement’s type of “as”.
- remaining properties that aren’t unique or overriden in FC<Props> declaration are destructured appropriately.
Environment information:
- @emotion/react 11.4.0
- @emotion/styled 11.3.0
- typescript 4.3.2
- React 16.9
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top GitHub Comments
I recommend using
React.HTMLAttributes<HTMLElement>
overReact.HTMLProps<HTMLElement>
because this is a type of props for<nav/>
element. I’m not exactly sure in what contextHTMLProps
should be used.It also seems that
HTMLProps<HTMLInputElement>
includes extra props (in contrast toHTMLAttributes<HTMLInputElement>
), like thedisabled
andrequired
props.So switching to
HTMLProps
worked for me in some components, but not all—I can alsoOmit<HTMLProps<HTMLInputElement>, "as">
but it’s not super nice.Did you end up solving this differently?
Edit:
Hm so I found this and it looks like the way to go would be
InputHTMLAttributes<HTMLInputElement>
. Works well on my end and I could clean up some oldOmit<>
🎉The only thing I’m not sure of is why some elements are missing their
*HTMLAttributes
types, likeul
. I assume that it’s because they don’t have any other props beyond theHTMLAttribute
type (all other element-specific generics extend it), so for these I’d just use it directly:HTMLAttributes<HTMLUListElement>
.