You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

扩展MUI调色板时出现Cannot read properties of undefined (reading 'dark')错误如何解决?

扩展MUI调色板时出现Uncaught TypeError: Cannot read properties of undefined (reading 'dark')错误

问题场景

在扩展Material UI调色板并使用自定义颜色时触发上述错误,相关代码如下:

theme.ts 文件

const theme = createTheme({
  palette: {
    primary: {
      main: "#ff4400",
    },
    custom: {
      light: "#ffa726",
      main: "#f57c00",
      dark: "#ef6c00",
      contrastText: "rgba(0, 0, 0, 0.87)",
    },
});
export default theme;

createPallete.d.ts 文件

import * as createPalette from "@mui/material/styles/createPalette";

declare module "@mui/material/styles" {
  interface Palette {
    custom: Palette["primary"];
  }

  // allow configuration using `createTheme`
  interface PaletteOptions {
    custom?: PaletteOptions["primary"];
  }
}

// Update the Button's color prop options
declare module "@mui/material/Button" {
  interface ButtonPropsColorOverrides {
    custom: true;
  }
}

自定义颜色使用代码

import { Button } from "@mui/material";

export const LoginMobilePage = () => {
  return (
    <>
        <Button variant="contained" color="custom">
          test for bgc
        </Button>
    </>
  );
};

解决方案

针对错误根源,逐一修复即可:

  • 修复theme.ts的语法错误
    你的createTheme对象末尾缺少两层闭合大括号,导致代码解析异常,补充后代码如下:

    const theme = createTheme({
      palette: {
        primary: {
          main: "#ff4400",
        },
        custom: {
          light: "#ffa726",
          main: "#f57c00",
          dark: "#ef6c00",
          contrastText: "rgba(0, 0, 0, 0.87)",
        },
      }, // 补充palette的闭合括号
    }); // 补充createTheme的闭合括号
    export default theme;
    
  • 调整类型定义的继承方式
    原类型定义中直接引用Palette["primary"]易导致类型推断异常,建议明确继承MUI内置的调色板类型,修改createPallete.d.ts如下:

    import * as createPalette from "@mui/material/styles/createPalette";
    
    declare module "@mui/material/styles" {
      interface Palette {
        custom: createPalette.PaletteColor;
      }
    
      interface PaletteOptions {
        custom?: createPalette.PaletteColorOptions;
      }
    }
    
    declare module "@mui/material/Button" {
      interface ButtonPropsColorOverrides {
        custom: true;
      }
    }
    
  • 确保类型文件被正确识别
    检查tsconfig.json的include数组,确认包含了createPallete.d.ts文件,示例配置:

    {
      "include": ["src/**/*", "createPallete.d.ts"]
    }
    

完成以上修复后,重新编译运行代码即可解决错误。


内容的提问来源于stack exchange,提问作者hossein ranjbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:25:03