error TS2322: Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

Issue

I’ve recently decided to move my codebase from JS to TS to add Type checking. I also use the styled-components library.

However, i’m running into the following issue:

error TS2322: Type '{ children: string; css: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.

Here is a basic code example:

import React from 'react'
const MyComponent: React.FC = (props) => {
    return (
        <div css={`
            padding: 44px;
        `}>
            My content
        </div>
    )
}

Please note that my tsconfig.json compilerOptions look like this:

"compilerOptions": {
        "composite": true,
        "declaration": true,
        "outDir": "./dist", // https://www.typescriptlang.org/tsconfig#outFile
        "rootDir": "./src",
        "jsx":"react",
        "types": ["@types/styled-components"],
        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        
        "declarationMap": true,
        "noEmitOnError": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "noUnusedLocals":true,
        "noUnusedParameters":true,
        "allowJs":true,
        "noEmit": false
    }

Can anyone point me in the right direction to solve the type of the css attribute ?

Solution

Create styledComponentsOverride.d.ts with following code inside:

import { CSSProp } from 'styled-components'

interface MyTheme {}

declare module 'react' {
    interface Attributes {
       css?: CSSProp<MyTheme>
    }
}

This will extend react element attributes types with optional CSS prop

more info: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31245

Answered By – jkaczmarkiewicz

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.