0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MUIのuseTheme()の戻り値を、カスタマイズした型に推論させる

Posted at

はじめに

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 で定義したカラーコードなどが型推論されることを確認できます。

カラーコードが型推論されている画像.png

また、ThemeProviderコンポーネントで正しく設定したthemeを渡すことで、UI描画にも正しく反映されます。

image.png

参照資料

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?