Custom Material Ui Theme [duplicate]

I am working with Material UI with TypeScript and want to add custom colors to my theme. Everything is working fine, except the VSCode linter that show me the next message.

Type '{ tan: string; lightRed: string; red: string; offBlack: string; white: string; }' is not assignable to type 'Partial<CommonColors>'.
  Object literal may only specify known properties, and 'tan' does not exist in type 'Partial<CommonColors>'.

In terms of develop and build is working fine, the only complain is the error message. I add a custom type to try to solve but it is not working.

const theme = createTheme({
  palette: {
    common: {
      tan,
      lightRed,
      red,
      offBlack,
      white,
    },
  },
});
import {
  PaletteOptions,
  CommonColors,
} from '@material-ui/core/styles/createPalette';

interface CustomColors extends CommonColors {
  tan: string?;
  lightRed: string;
  red: string;
  offBlack: string;
}

declare module '@material-ui/core/styles/createPalette' {
  export interface PaletteOptions {
    common: CustomColors;
  }
}

I added to the tsconfig.json file. The tan, red and the rest of values are declared as Strings. Any clue about how can I solve this? Thanks in advance.


Solution 1:

I can't claim to have a good understanding of module augmentation, but I have done it in my own app (also for custom colors in the palette) and when I use the same approach as in my own app, it works for your scenario. My understanding is that you only have to specify the augmentation -- you don't need to create new types extending the existing ones. In your case, you just want to augment CommonColors.

The following approach seems to work:

import "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
  interface CommonColors {
    tan: string;
    lightRed: string;
    red: string;
    offBlack: string;
  }
}

Edit TypeScript custom colors

In my example, I placed this code in a createPalette.d.ts file and the name of that file does seem to matter (though it doesn't seem to matter what directory it is in as long as it is within the directories looked at by the compiler). It also works fine to put the code directly in index.tsx or directly in the TypeScript file that executes createTheme.

Related answers:

  • Typescript Module augmentation is not working: Property 'main' does not exist on type 'PaletteColorOptions'
  • MUI Override Slider color options with module augmentation