材质 UI 使用打字稿在调色板的主对象上定义新属性



我正在尝试使用MUI v5自定义主题,以使其在我的项目中发挥作用,到目前为止,我可以根据我的需求自定义我的主题,但现在的问题是,我需要向调色板中定义的主对象添加一个新属性,默认情况下,调色板中的每个对象都应该有4个主要属性-

light?: string;
main: string;
dark?: string;
contrastText?: string;

但是,如果我想像";魔术"?

主题.ts

import { createTheme, Theme } from "@mui/material/styles";
import { brown, red } from "@mui/material/colors";
declare module "@mui/material/styles/createPalette" {
interface Palette {
brown: PaletteColor;
}
interface PaletteOptions {
brown: PaletteColorOptions;
}
}
declare module "@mui/material/styles" {
// fix the type error when referencing the Theme object in your styled component
interface Theme {
myField?: {
myNestedField?: string;
};
}
// fix the type error when calling `createTheme()` with a custom theme option
interface ThemeOptions {
myField?: {
myNestedField: {
margin?: string;
};
};
}
}
export const theme = createTheme({
palette: {
primary: {
main: "#ffffff",
magic:'#000000 ///throws error - 
},
brown: {
main: brown[300],
},
},
myField: {
myNestedField: { margin: "10px 5px" },
},
});

所以当我定义";魔术;在parimary内部,我得到错误

类型"{main:string;magic:string!}"不可分配给类型'调色板颜色选项|未定义'。对象文字只能指定已知属性,并且类型中不存在"magic"调色板颜色选项"。

PaletteColorOptionstype,而不是interface,所以我们不能对它使用模块扩充。但幸运的是,它由两个接口组成:type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial。因此,我们可以像这样扩充接口SimplePaletteColorOptions

declare module '@mui/material/styles/createPalette' {
interface SimplePaletteColorOptions {
magic: string
}
}

最新更新