带 Typescript 的样式组件:主题变量缺少类型

Chi*_*hip 5 typescript reactjs styled-components

theme变量的类型any位于顶层。如果我theme在一个css''块中使用它,它就会得到正确的输入DefaultTheme

例子:

const Header = styled.div<{ invertedColor: boolean }>`
  color: ${({ theme }) => theme.color.blue}; // theme = any

  ${({ invertedColor }) =>
    invertedColor &&
    css`
      color: ${({ theme }) => theme.color.white}; // theme = DefaultTheme (correct)
    `}
`
Run Code Online (Sandbox Code Playgroud)

因为在这里也<{ invertedColor: boolean }>无法工作。invertedColorany

我添加了styled-components.d.ts以下内容:

import 'styled-components';

type ColorType = 'blue' | 'white';

declare module 'styled-components' {
  export interface DefaultTheme {
    color: Record<ColorType, string>;
  }
}
Run Code Online (Sandbox Code Playgroud)

使用以下版本:

"@types/styled-components": "^5.1.22",
"styled-components": "^5.3.3",
Run Code Online (Sandbox Code Playgroud)

我尝试调试和检查类型丢失的位置,因为它在 - 处正确传递ThemeProvider- 也尝试了这里的每个解决方案: https: //github.com/styled-components/styled-components/issues/1589

调试它的最佳方法是什么?有什么提示吗?

Yil*_*maz 0

设置颜色类型正确。

看起来打字稿无法识别您的声明模块。我使用了相同版本的样式组件,但styled-components.d.ts我创建了styled.d.ts文件而不是 ,并且没有任何问题