TypeScript:如何将DefaultTheme与有样式的组件结合?



我有一个模块是用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,
}

我也复制了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};
`

最新更新