Material UI define a new property on palette's primary object with typescript

Viewed 997

I am trying to play around with MUI v5 custome theme to get it working in my project, so far i am able to customize my theme as per my needs, but now the issue is that i need to add a new property to my primary object defined inside palette, by default each object in paletter is supposed to have 4 main properties -

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

but what if i want to add a new property to it like "magic" ?

theme.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" },
  },
});

so when i define "magic" inside parimary i get the error

Type '{ main: string; magic: string; }' is not assignable to type 'PaletteColorOptions | undefined'. Object literal may only specify known properties, and 'magic' does not exist in type 'PaletteColorOptions'.

1 Answers

PaletteColorOptions is a type – not an interface so we can't use module augmentation on it. But luckily it's made up of the composition of two interfaces: type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial. So we can augment interface SimplePaletteColorOptions like so:

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