Search code examples
typescriptstyled-components

Styled components's 'css' prop with TypeScript


styled-components have a plugin that allows for the following:

<div
  css={`
    background: papayawhip;
    color: ${props => props.theme.colors.text};
  `}
/>

Is there any way I can tell TypeScript css is a valid property on all elements?


Solution

  • Add following line to a TypeScript file inside your project as described in this issue:

    // e.g. src/global.d.ts
    
    import {} from "styled-components/cssprop"
    // or TS 3.8+
    import type {} from "styled-components/cssprop"
    

    Alternatively you can manually augment the react module type declaration - copy/paste contents from "styled-components/cssprop" to above file:

    import { CSSProp } from "styled-components"
    
    interface MyTheme {} // declare custom theme type
    
    declare module "react" {
      interface Attributes {
        css?: CSSProp<MyTheme>
      }
    }
    

    Latter variant will also allow you to customize the css prop theme type.