Home > Software engineering >  MUI v5: Override members of type ColorPartial to createTheme
MUI v5: Override members of type ColorPartial to createTheme

Time:12-22

I would like to override some members in PaletteOptions.

I'm trying to change the type of grey from ColorPartial to PaletteColorOptions so I can add more members.

I tried the code below.

declare module '@mui/material/styles' {
  interface PaletteOptions {
    grey: {
      main: string;
      light: string;
      dark: string;
    };
  }
}

const theme = createTheme({
  palette: {
    grey: {
      dark: '#777',
      main: '#888',
      light: '#999',
    },
  },
});

export default theme;

I get this error.

TS2687: All declarations of 'grey' must have identical modifiers. TS2717: Subsequent property declarations must have the same type. Property 'grey' must be of type 'Partial | undefined', but here has type '{ main: string; light: string; dark: string; }'. createPalette.d.ts(114, 3): 'grey' was also declared here.

TS2322: Type '{ dark: string; main: string; light: string; }' is not assignable to type 'Partial'.   Object literal may only specify known properties, and 'dark' does not exist in type 'Partial'.

Is there a way to do this?

CodePudding user response:

You're using module augmentation on PaletteOptions but you're not adding any new types to that interface; instead, you're adding new types to Color. You need to add module augmentation for Color so that PartialColor === Partial<Color> can pick it up. Like so:

import { createTheme, ThemeOptions } from '@mui/material'

declare module '@mui/material' {
  interface Color {
    dark: string
    main: string
    light: string
  }
}

const themeOptions: ThemeOptions = {
  palette: {
    grey: {
      dark: '#777',
      main: '#888',
      light: '#999',
    },
  },
}

const theme = createTheme(themeOptions)

export default theme
  • Related