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 ?
CodePudding user response:
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
CodePudding user response:
Thanks @jkaczmarkiewicz ! This works great. Updated it to :
import { CSSProp } from "styled-components";
interface DefaultTheme {}
declare module "react" {
interface HTMLAttributes<T> extends DOMAttributes<T> {
css?: CSSProp<DefaultTheme>;
}
}
In addition to the link you provided, this issue might help others too.