Material UI v4: extending PaletteColorOptions

Viewed 706

I want to do something very straightforward in Material UI v4's (v4.11) palette: add a new field to PaletteColorOptions. Let's say I want to add darker?: string

This is the type definition in the relevant Material UI module:

createPalette.d.ts

export type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial;

export interface SimplePaletteColorOptions {
  light?: string;
  main: string;
  dark?: string;
  contrastText?: string;
}

There is a merged PR to Material UI which adds to their documentation an example of how to add a new Palette Color Option via module augmentation. This is what they suggest:

declare module '@material-ui/core/styles/createMuiTheme' {
  interface PaletteColor {
    darker?: string
  }
  interface SimplePaletteColorOptions {
    darker?: string
  }
}

I tried this but it doesn't seem to work - I'm getting the following error when trying to add darker to one of the color objects - suggesting that I did not manage to add the new field to PaletteColorOptions

Type '{ dark: string; main: string; contrastText: string; darker: string; }' is not assignable to type 'PaletteColorOptions | undefined'. Object literal may only specify known properties, and 'darker' does not exist in type 'PaletteColorOptions'.ts(2322) createPalette.d.ts(105, 3): The expected type comes from property 'primary' which is declared here on type 'PaletteOptions'

I also tried to add similar definitions to the createPalette module (again via module augmentation as suggested in the example above), but I'm getting the same TypeScript error shown above.

declare module '@material-ui/core/styles/createPalette' {
  interface PaletteColor {
    darker?: string
  }
  interface PaletteColorOptions {
    darker?: string
  }
}

Any guidance would be appreciated.

1 Answers

I managed to solve it in the end. Here is how I did it:

palette.ts (a file we had created to define the palette)

interface ExtendedPaletteColorOptions extends SimplePaletteColorOptions {
  darker?: string
}

interface ExtendedPaletteOptions extends PaletteOptions {
  primary: ExtendedPaletteColorOptions
  secondary: ExtendedPaletteColorOptions
  text: Partial<TypeText>
  error: ExtendedPaletteColorOptions
  warning: ExtendedPaletteColorOptions
  info: ExtendedPaletteColorOptions
  success: ExtendedPaletteColorOptions
  // And your custom palette options if you defined them, e.g:
  // brand: ExtendedPaletteColorOptions
}

const palette: ExtendedPaletteOptions = {
  // Our palette, which now supports the new `lighter`, for example:
  primary: {
    main: '#555555',
    dark: '#333333',
    darker: '#111111',
  }
}

theme.d.ts (a file we had created for module augmentation of the material-ui modules)

declare module '@material-ui/core/styles/createPalette' {
  interface PaletteColor {
    lighter: string
  }
}
Related