How to use forwardedAs prop with styled-components? Using forwardedAs prop with typescript

Here are the docs on forwardedAs prop: https://styled-components.com/docs/api#forwardedas-prop.

As you can see, it’s not very detailed and does not show how to properly use this prop.

My question is: How can I access the props that are sent down via forwardedAs? How can I define types for these forwardedAs props?

I’m able to access the forwardedAs props via ...rest parameters, but I need to define types for these props since I am also using styled-components with Typescript.

Here’s my code example:

// Button.jsx
const myPropsToForward = {
  href: 'https://somewebsite.com',
  // ...more props
}

const Button = styled.button`
  // ...button styles
`

const myComponent = () => (
  <Button
    as={Link}
    to={ctaLink}
    forwardedAs={myPropsToForward}
  />
)

// Link.jsx
const Link = ({
  forwardedAs,
  ...rest
}) => {
  // How do I access the forwardedAs prop from <Button /> here?

  return (
    <a href={forwardAs?.href} {...rest} />
  )
}

Here, I need to be able to access the props within the Link component sent down via forwardedAs prop, but there’s no documentation on how to do that. If I can access the forwardedAs prop, I can then define proper types for the Link component. I do not want to rely on the ...rest parameter as I cannot define types for that.

Thank you in advance.

161 thoughts on “How to use forwardedAs prop with styled-components? Using forwardedAs prop with typescript”