Home > Software engineering >  Exclude colors from Material UI theme
Exclude colors from Material UI theme

Time:01-03

Is it possible to exclude some color types from MUI palette (MUI v5)? Let's say, I want to exclude background and error colors, and I want to be able to use only colors declared in my custom theme file.

I tried with never but it doesn't solve my problem

declare module '@mui/material/styles' {
  interface Palette {
    primary: Palette['primary'];
    secondary: Palette['primary'];
    background: never;
    error: never;  
  }
}

CodePudding user response:

Would overriding the default Palette like this be a solution ?

interface CustomPalette extends Palette {
  background?: never;
  error?: never;
}

Of course you need to set this interface to your components or it will still use MUI default palette

CodePudding user response:

I believe what you want to do is the opposite of module augmentation, however, I'm not sure if it is possible to do in the current stage of TypeScript.

What you can do instead is to overwrite MUI types with unwanted props omitted.

In this case, remove the palette and then re-add it with unwanted properties omitted from it. An example of that would be:

import { useTheme as useMuiTheme, Theme as MuiTheme } from "@mui/material";

interface Theme extends Omit<MuiTheme, "palette"> {
    palette: Omit<MuiTheme["palette"], "primary">;
}

const useTheme = () => {
    const theme = useMuiTheme();
    return theme as Theme;
};

export default useTheme;

And then use your own version of useTheme throughout the codebase.

  • Related