TypeScript:如何将 DefaultTheme 与样式组件结合起来?

TypeScript: How to combine DefaultTheme with styled-components?

我有一个用 styled-componentsexport a theme

制作的模块

我想将模块样式的导出主题与我的应用程序主题结合起来。

我在 theme.ts 中尝试了以下方法:

import { theme as idCheckTheme } from '@pass-culture/id-check/src/theme'
import { DefaultTheme } from 'styled-components/native'
import './styled.d'

export const theme: DefaultTheme = {
  ...idCheckTheme,
  appBarHeight: 64,
}


我也复制了 styled.d.ts 并在顶部添加了 appBarHeight: number

当我启动我的应用程序时,出现以下错误:

Property 'appBarHeight' is missing in type '{ colors: { black: ColorsEnum; error: ColorsEnum; greenValid: ColorsEnum; greyDark: ColorsEnum; greyMedium: ColorsEnum; greyLight: ColorsEnum; ... 4 more ...; primaryDark: ColorsEnum; }; typography: { ...; }; buttons: { ...; }; }' but required in type 'DefaultTheme'.  TS2741

我希望它能正常工作,在 IntelliJ 中打字不会报错。

如何使用 TypeScript 将 styled-components 主题组合成新的 DefaultTheme

您应该能够扩展 DefaultTheme 接口,为您的主题创建一个接口,并像这样定义它:

import { theme as idCheckTheme, ThemeType as IdCheckThemeType } from '@pass-culture/id-check/src/theme'
import { DefaultTheme } from 'styled-components/native'

// a declaration (d.ts) file may work better than declaring this above the interface
declare module 'styled-components' {
  export interface DefaultTheme extends INewTheme {}
}

export interface INewTheme extends IdCheckThemeType{
  appBarHeight: number;
}

export const NewTheme: INewTheme = {
  ...idCheckTheme,
  appBarHeight: 64,
}
 
// pass your theme to your theme provider
<ThemeProvider theme={NewTheme}>
<App/>
</ThemeProvider>

在您的样式组件中,您还应该能够像这样访问 appBarHeight:

const StyledBar = styled.div`
  ${({theme}) => theme.appBarHeight};
`