使用 Typescript 在 Material-UI 中的 createMuiTheme 中向背景属性添加属性

Dee*_*ens 3 javascript typescript reactjs material-ui typescript-typings

我正在尝试在 createMuiTheme 中添加一个新属性。但 Typescript 不让我这样做。

\n

我按照此处的说明进行操作:https ://next.material-ui.com/guides/typescript/#customization-of-theme

\n

我创建了一个 .ts 文件,将其放置在其中:

\n
import * as React from \'react\';\n\ndeclare module \'@material-ui/core/styles\' {\n  interface TypeBackground {\n    darker: string;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

并且,这是我创建 Material-UI 主题的地方:

\n
import {createMuiTheme} from "@material-ui/core";\n\nexport const darkTheme = createMuiTheme({\n    palette: {\n        background: {\n            darker: \'#fafa\',\n        },\n        mode: \'dark\'\n    },\n})\n
Run Code Online (Sandbox Code Playgroud)\n

但我收到此错误:

\n
TS2322: Type \'{ darker: string; }\' is not assignable to type \'Partial<TypeBackground>\'. \xc2\xa0\xc2\xa0Object literal may only specify known properties, and \'darker\' does not exist in type \'Partial<TypeBackground>\'\n
Run Code Online (Sandbox Code Playgroud)\n

即便如此,我还是尝试了material-ui团队的示例,它可以工作,但不是我的代码。我找不到原因。我可能应该错过一些东西。

\n

我正在使用接口“TypeBackground”,因为它的命名类似于material-ui 中的createPalette.d.ts 文件中的名称。

\n
TS2322: Type \'{ darker: string; }\' is not assignable to type \'Partial<TypeBackground>\'. \xc2\xa0\xc2\xa0Object literal may only specify known properties, and \'darker\' does not exist in type \'Partial<TypeBackground>\'\n
Run Code Online (Sandbox Code Playgroud)\n

所以我也尝试做同样的事情。我认为这与向调色板属性添加道具相同。

\n

谢谢!

\n

Dee*_*ens 6

好的,所以我刚刚找到了解决方案。但我真的不明白为什么它有效。

我修改了“声明模块”行:

declare module '@material-ui/core/styles/createPalette'
Run Code Online (Sandbox Code Playgroud)

我刚刚在样式后面添加了“createPalette”。现在它可以工作了,我只是不明白为什么^^!