【问题标题】:error TS2322: Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'错误 TS2322:“DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>”类型上不存在属性“css”
【发布时间】:2022-01-04 16:42:46
【问题描述】:

我最近决定将我的代码库从 JS 移动到 TS 以添加类型检查。我也使用styled-components 库。

但是,我遇到了以下问题:

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>'.

这是一个基本的代码示例:

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

请注意我的tsconfig.json compilerOptions 看起来像这样:

"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
    }

谁能指出我解决css属性类型的正确方向?

【问题讨论】:

  • 您要查找的属性是style 而不是css

标签: reactjs typescript styled-components


【解决方案1】:

为什么不直接在 'style.d.ts' 文件中添加这一行?

import {} from 'styled-components/cssprop'

【讨论】:

    【解决方案2】:

    感谢@jkaczmarkiewicz!这很好用。将其更新为:

    import { CSSProp } from "styled-components";
    
    interface DefaultTheme {}
    
    declare module "react" {
       interface HTMLAttributes<T> extends DOMAttributes<T> {
         css?: CSSProp<DefaultTheme>;
       }
     }
    

    除了您提供的链接之外,此issue 也可能对其他人有所帮助。

    【讨论】:

      【解决方案3】:

      用下面的代码创建styledComponentsOverride.d.ts

      import { CSSProp } from 'styled-components'
      
      interface MyTheme {}
      
      declare module 'react' {
          interface Attributes {
             css?: CSSProp<MyTheme>
          }
      }
      

      这将使用可选的 CSS 属性扩展 react 元素属性类型

      更多信息:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31245

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 2022-09-23
        • 2018-02-23
        • 1970-01-01
        • 2017-08-18
        • 1970-01-01
        • 2019-11-30
        • 2019-11-26
        • 2021-06-17
        相关资源
        最近更新 更多