Search code examples
reactjstypescriptstyled-componentsreact-propstsx

Getting 'is not assignable to type' error on react component, how can I understand it better?


I'm building this component to test out react-spring library. I started it on codesandbox then pulled it locally to my pc. When I pulled it down this error came up and I am not sure how to interpret it or what is causing it. I'm pretty new to typescript so any help is much appreciated.

At first, I thought it could be wrong type for children prop, but then realized it's actually width and height, now I am not sure if it's a styled-components (since the error appears under StyledCard) or if when you use a children render prop method you have to specify your types differently..

import * as React from "react"
import styled from "styled-components"

const StyledCard = styled.div`
  width: ${(props: any) => props.width}px;
  height: ${(props: any) => props.height}px;
  box-shadow: 0px 2px 4px -1px rgba(0, 0, 0, 0.2),
    0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12);
  text-align: center;
`

interface ICardProps {
  children?: React.ReactNode
  width?: number
  height?: number
}

const Card: React.FC<ICardProps> = ({ width, height, children }) => {
  return (
    <StyledCard width={width} height={height}>
      {children}
    </StyledCard>
  )
}

export default Card

This is the error I get:

Type '{ children: ReactNode; width: number | undefined; height: number | undefined; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "style" | "title" | "key" | "defaultChecked" | "defaultValue" | ... 246 more ... | "onTransitionEndCapture"> & { ...; }, "style" | ... 251 more ... | "onTransitionEndCapture"> & Partial<...>, "style" | ... 251 mor...'.
  Property 'width' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "style" | "title" | "key" | "defaultChecked" | "defaultValue" | ... 246 more ... | "onTransitionEndCapture"> & { ...; }, "style" | ... 251 more ... | "onTransitionEndCapture"> & Partial<...>, "style" | ... 251 mor...'.ts(2322)

Solution

  • In order for Typescript to know what custom props you are going to pass down to your styled div, you need let it know with a type parameter like this:

    interface StyledCardProps {
        width?: number
        height?: number
    }
    
    const StyledCard = styled.div<StyledCardProps>`
        // your css here
    `