Javascript – TypeScript: Extend React component props for styled component element

javascript, reactjs, styled-components, typescript

i'm trying to extend a react components props in TypeScript so that it contains all the normal html button attributes, as well as react specific stuff like ref

My understanding is that the type React.HTMLProps is what i need, (React.HTMLAttributes doesn't contain ref)

However, when trying to pass my props to a styled component the compiler complains.

My attempt 👇🏼 Codesandbox example:

enter image description here

Best Solution

Couple of things.

Change the typing to:

interface Props extends React.ComponentPropsWithoutRef<'button'> {  loading?: boolean  secondary?: boolean  fullWidth?: boolean}

That should fix the issue for you. I forked your sandbox and it gets rid of the error.

There is also a SO post that this come from that you can use: Using a forwardRef component with children in TypeScript - the answer details one way but also mentions the answer 1.