使用 typescript 的 EmotionJS 不会将主题类型传递给样式组件中的 props

Twi*_*geh 7 emotion typescript

情感.d.ts

import '@emotion/react';

declare module '@emotion/react' {
    export interface Theme {
        colors: {
            primaryColor: string;
            accentColor: string;
        };
    }
}

Run Code Online (Sandbox Code Playgroud)

应用程序.tsx

import { Theme, ThemeProvider } from '@emotion/react';

const theme: Theme = {
    colors: {
        accentColor: 'hotpink',
        primaryColor: 'aqua',
    },
};
...

return (
<ThemeProvider theme={theme}>

...

Run Code Online (Sandbox Code Playgroud)

按钮.tsx

const StyledButton = styled.a`
    ${({ theme }) =>
        `background-color: ${theme.colors.accentColor};`
    }`;
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

import '@emotion/react';

declare module '@emotion/react' {
    export interface Theme {
        colors: {
            primaryColor: string;
            accentColor: string;
        };
    }
}

Run Code Online (Sandbox Code Playgroud)
src
|=>@types
  |> emotion.d.ts
|=> components
|> App.tsx
Run Code Online (Sandbox Code Playgroud)

属性“颜色”在类型“对象”上不存在。

我做错了什么还是我误读了文档?

现在,我通过将主题传递给样式构造函数来手动添加主题:


type StyledProps = Pick<ButtonProps, 'bgColor' | 'fColor'> & { theme: Theme };

const StyledButton = styled.a<StyledProps>`
...
Run Code Online (Sandbox Code Playgroud)

删除传递的类型也没有帮助。

似乎 d.ts 文件已正确拾取,因为我可以从"@emtion/react"with导入正确的主题类型并使用它在样式组件中import { Theme } from "@emotion/react"键入props.theme

再现

tmh*_*005 4

根据您提供的代码,我认为错误应该是:

Property 'accentColor' does not exist on type 'Theme'. // instead of object
Run Code Online (Sandbox Code Playgroud)

无论如何,您的Theme对象现在嵌套colors在顶层,因此您可以更改为:

Property 'accentColor' does not exist on type 'Theme'. // instead of object
Run Code Online (Sandbox Code Playgroud)

请记住,您还需要在构建过程中包含您定义的类型tsconfig.json通过选项将您定义的类型包含在文件的构建过程中include

关于无法覆盖的更新Theme通过自定义类型文件覆盖的更新

正如我所见,该styled类型仅消耗Theme来自的对象@emotion/react至少来自 version 的^11.0.0

简而言之,您必须@emotion/styled从该版本更新到^11.0.0它才能按预期工作:

{
  "dependencies": {
    // ...
    "@emotion/styled": "^11.0.0",
  }
}
Run Code Online (Sandbox Code Playgroud)