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

Dim*_*iwa 4 javascript typescript reactjs tsx styled-components

我有一个使用主题制作styled-components导出主题的模块

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

我已经尝试过以下操作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,
}


Run Code Online (Sandbox Code Playgroud)

我还复制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
Run Code Online (Sandbox Code Playgroud)

我期望它能够工作,在 IntelliJ 中打字不会抱怨。

如何使用 TypeScript 将styled-components主题合并到新主题中DefaultTheme

Jam*_*ero 5

您应该能够扩展 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>
Run Code Online (Sandbox Code Playgroud)

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

const StyledBar = styled.div`
  ${({theme}) => theme.appBarHeight};
`
Run Code Online (Sandbox Code Playgroud)