Search code examples
reactjstypescriptstyled-components

Trouble on creating a Component wrapper using styled-component and TypeScript


Creating a components library, I wanted to include the layout components directly in the library. For that I just created the classics component (Container, Row and Col) which is actually just a copy of the ones from the library react-grid-system.

So for example, my component Col look like that:

import React from 'react'
import styled from 'styled-components'
import { Col as ReactGridSystemCol, ColProps } from 'react-grid-system';

// C O M P O N E N T
const Col: React.FunctionComponent<ColProps> = (props) => {
  const { children } = props

  return (
    <StyledCol {...props}>
      {children}
    </StyledCol>
  )
}

// S T Y L E S
const StyledCol = styled<ColProps>(ReactGridSystemCol)` // <- Type 'ColProps' does not satisfy the constraint '"symbol" | "object" ...
  /* ... */
`

StyledCol.displayName = 'StyledCol'

export default Col

Logically, I say that my StyledCol component inherits from the ReactGridSystemCol component, so I will be able to add styles to this one and it will be rendered in my jsx.

Then I have to manage the props that my Col component can receive. They are exactly the same as those of ReactGridSystemCol, so I use the type of the library, ColProps.

I then indicate that StyledCol can receive this props using styled<ColProps>(ReactGridSystemCol).

The problem is that visibly there is a type error because typescript returns this error:

Type 'ColProps' does not satisfy the constraint '"symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | ... 157 more ... | FunctionComponent<...>'.
  Type 'ColProps' is not assignable to type 'FunctionComponent<any>'.
    Type 'ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & { width?: string | number | undefined; ... 5 more ...; component?: (() => string) | undefined; } & Partial<...>' provides no match for the signature '(props: any, context?: any): ReactElement<any, any> | null'.

I don't quite understand my mistake here so if you have any ideas I'd be very grateful.


Solution

  • Try something like this.

    const StyledCol = styled(ReactGridSystemCol)<ColProps>``