リテラル型

リテラル型は、特定の値そのものだけを許容する型です。型の厳密さを高め、意図しない代入を防ぐ際に使われます。


📋 リテラル型の種類と例

型の種類 説明 使用例
文字列リテラル 特定の文字列のみ許可する const color: "red" = "red";
数値リテラル 特定の数値のみ許可する const level: 1 = 1;
真偽値リテラル true または false const flag: true = true;

🧪 使用例

type Direction = "up" | "down" | "left" | "right";

function move(dir: Direction): void {
  console.log(`Moving ${dir}`);
}

const current: Direction = "left"; // ✅ OK
// const invalid: Direction = "top"; // ❌ エラー

💡 ユースケース

  • オプション値の列挙
  • 関数の引数制限
  • Redux の Action タイプ
  • API の定数パラメータ

🧷 補足:as const との併用

リテラル型をオブジェクトリテラルで保持したい場合は as const を使うと便利です。

const config = {
  mode: "dark",
  lang: "ja"
} as const;

type Mode = typeof config.mode; // "dark"

✅ まとめ

  • リテラル型は「値を型として扱う」ことで安全性を高める
  • "success" | "error" のようなユニオン型と併用されることが多い
  • 自由な文字列より選択肢を限定したいときに最適
コメントを残す 0

Your email address will not be published. Required fields are marked *