我有一个由
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};
`
FWIW,当我将 NextJS 文件升级到 V12 时,我遇到了同样的问题。我一直遇到这个问题,终于弄清楚是什么原因造成的。
我的
tsconfig.json
文件有一个值 "incremental": true
。当我查找它时,我发现它保存了以前的编译文件,然后使用这些保存的文件作为起点“增量”构建可执行文件。一旦我删除了该选项,我的构建和测试就完美地工作了。
我猜有一些旧的编译文件 Typescript 不知道扔掉,这导致了问题?
疯狂,但它确实解决了我的问题。