使用TypeScript样式化组件的'css'属性

时间:2020-03-31 14:14:01

标签: typescript styled-components

styled-components有一个允许以下操作的插件:

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

有什么办法可以告诉TypeScript css是所有元素上的有效属性?

1 个答案:

答案 0 :(得分:6)

按照this issue中所述,将以下行添加到项目内的TypeScript文件中:

// e.g. src/global.d.ts

import {} from "styled-components/cssprop"
// or TS 3.8+
import type {} from "styled-components/cssprop"

或者,您可以手动扩展react模块类型声明-将内容从"styled-components/cssprop"复制/粘贴到上述文件中:

import { CSSProp } from "styled-components"

interface MyTheme {} // declare custom theme type

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

最近的变体也将允许您自定义css道具主题类型。