はじめに
MUIでは Theme provider を利用して、MUIから提供されているデフォルトのtheme objectをカスタマイズすることができます。
しかし、型推論では、カラーコードなど具体的な設定値が取得されません。この記事では、useTheme()
の戻り値をカスタマイズした型に推論させる方法を紹介します。
theme object にオリジナルのプロパティを追加したい場合、モジュール拡張 (module augmentation)を行う必要があります。
詳細は以下の公式ドキュメントをご確認ください。
https://mui.com/material-ui/customization/theming/#typescript
コード例
以下は、useTheme()
の型をカスタマイズするコード例です。
import { createTheme, type Theme } from "@mui/material/styles";
type CreateThemeOptions = Parameters<typeof createTheme>[0];
// theme variables をカスタマイズする
const themeOptions = {
palette: {
text: {
primary: "#1A1A1C",
secondary: "#626264",
disabled: "#949497",
},
},
typography: {
fontFamily: [
'"Noto Sans JP Variable"',
"-apple-system",
].join(","),
},
} as const satisfies CreateThemeOptions;
export const theme = createTheme(themeOptions);
/**
* カスタマイズされた theme のリテラルを含む型
*/
type CustomizedTheme = typeof themeOptions & Theme;
// モジュール拡張
declare module "@mui/material/styles" {
/**
* `useTheme` のジェネリクス型を上書きする。
* @example
* ```ts
* import { useTheme } from "@mui/material/styles";
* const theme = useTheme();
* // `theme` は `CustomizedTheme` に推論される
* ```
*/
export function useTheme<T = CustomizedTheme>(): T;
}
補足
-
themeOptions
はカスタマイズされたオプションを保持するオブジェクトであり、その型情報がリテラル型として保持されます。 -
CustomizedTheme
により、MUIのTheme
型とthemeOptions
のリテラル型を結合します。 -
useTheme
を上書きすることで、themeOptions
の型が推論されるようになります。
型推論の動作確認
const theme = useTheme();
を利用すると、themeOptions
で定義したカラーコードなどが型推論されることを確認できます。
また、ThemeProviderコンポーネントで正しく設定したthemeを渡すことで、UI描画にも正しく反映されます。
参照資料