LoginSignup
12
5

More than 1 year has passed since last update.

Material-UIのPaletteをカスタマイズした時の型定義について - TypeScript

Last updated at Posted at 2022-02-19

React/TypeScriptで、MUIのPaletteをカスタマイズする方法を調べてみました。
そこで型定義をする必要があったので、その方法を共有したいと思います。

##Material-UIのversion

  • @mui/material@5.3.0

まずPaletteにキーワードを追加してカスタマイズ

MUIのThemeでは、palette内でprimary: blueなどと設定することがありますが、デフォルトの項目以外を設定したいときがあります。
自分はborder-colorで使うmainカラーを設定したかったので、borderキーワードを追加しました。

theme.js
const theme = createTheme({
  palette: {
    primary: {
      main: '#4ea6cc',
    },
    secondary: {
      main: '#e6ee9c',
    },
// ここで設定
    border: {
      main: '#e0e0e0',
    },
  },
});

しかし、このままだと「'border' は型 'PaletteOptions' に存在しません。」とエラーになります。
スクリーンショット 2022-02-19 18.17.09.png

Paletteの型定義を拡張する

この場合、Paletteの型定義されているinterface PaletteOptionsを拡張する必要があります。

PaletteではcreatePalette.d.tsという型定義ファイルでPaletteOptionsというinterfaceが宣言されています。

createPalette.d.ts
...

export interface Palette {
  common: CommonColors;
  mode: PaletteMode;
  contrastThreshold: number;
  tonalOffset: PaletteTonalOffset;
  primary: PaletteColor;
  secondary: PaletteColor;
  error: PaletteColor;
  warning: PaletteColor;
  info: PaletteColor;
  success: PaletteColor;
  grey: Color;
  text: TypeText;
  divider: TypeDivider;
  action: TypeAction;
  background: TypeBackground;
  getContrastText: (background: string) => string;
  augmentColor: (options: PaletteAugmentColorOptions) => PaletteColor;
}

...

export interface PaletteOptions {
  primary?: PaletteColorOptions;
  secondary?: PaletteColorOptions;
  error?: PaletteColorOptions;
  warning?: PaletteColorOptions;
  info?: PaletteColorOptions;
  success?: PaletteColorOptions;
  mode?: PaletteMode;
  tonalOffset?: PaletteTonalOffset;
  contrastThreshold?: number;
  common?: Partial<CommonColors>;
  grey?: ColorPartial;
  text?: Partial<TypeText>;
  divider?: string;
  action?: Partial<TypeAction>;
  background?: Partial<TypeBackground>;
  getContrastText?: (background: string) => string;
}
...

この型定義ファイル内のinterfaceを拡張したい場合、declare moduleを使います。(PalettePaletteOptionsの両方を拡張します)

theme.ts
declare module '@mui/material/styles' {
  interface Palette {
    border: {
      main: string;
    };
  }
  interface PaletteOptions {
    border?: {
      main?: string;
    };
  }
}

const theme = createTheme({
  palette: {
    primary: {
      main: '#4ea6cc',
    },
    secondary: {
      main: '#e6ee9c',
    },
    border: {
      main: '#e0e0e0',
    },
  },
});

declare moduleでinterfaceを拡張することで、Themeの型を定義することができました。

##参考にさせていただいたURL

12
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5