TypeScriptのリテラル型は、特定の値のみを型として許容する強力な機能です。この記事では、リテラル型の基本的な使い方から実践的な活用方法まで、具体例を交えて解説します。

リテラル型とは

リテラル型は、特定の値そのものを型として使用できる機能です。文字列、数値、真偽値などの具体的な値を型として定義することができます。

let status: "success" | "error" | "pending";
let level: 1 | 2 | 3;
let isEnabled: true;

リテラル型の基本的な使い方

文字列リテラル型

// 特定の文字列のみを許容する型を定義
type Direction = "north" | "south" | "east" | "west";

// 正しい使用例
const direction: Direction = "north"; // OK

// エラーになる例
const invalidDirection: Direction = "northwest"; // エラー

数値リテラル型

// 特定の数値のみを許容する型を定義
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

// 正しい使用例
const roll: DiceRoll = 6; // OK

// エラーになる例
const invalidRoll: DiceRoll = 7; // エラー

実践的な活用例

APIのステータスコード定義

type HttpSuccessStatus = 200 | 201 | 204;
type HttpErrorStatus = 400 | 401 | 403 | 404 | 500;

interface ApiResponse {
  status: HttpSuccessStatus | HttpErrorStatus;
  data?: any;
  error?: string;
}

設定オプションの型定義

type Theme = "light" | "dark" | "system";
type Language = "en" | "ja" | "es";

interface UserPreferences {
  theme: Theme;
  language: Language;
}

const preferences: UserPreferences = {
  theme: "light",    // OK
  language: "ja"     // OK
};

リテラル型とユニオン型の組み合わせ

リテラル型は、ユニオン型と組み合わせることで、より柔軟な型定義が可能になります。

type ButtonSize = "small" | "medium" | "large";
type ButtonVariant = "primary" | "secondary" | "outline";

interface ButtonProps {
  size: ButtonSize;
  variant: ButtonVariant;
  label: string;
}

const button: ButtonProps = {
  size: "medium",
  variant: "primary",
  label: "Click me"
};

リテラル型のベストプラクティス

1. 定数との組み合わせ

const VALID_STATUSES = ["draft", "published", "archived"] as const;
type Status = typeof VALID_STATUSES[number];

2. 型安全な関数パラメータ

function setVolume(level: 0 | 0.25 | 0.5 | 0.75 | 1) {
  // 実装
}

3. オブジェクトのプロパティ制限

interface Config {
  mode: "development" | "production";
  debug: boolean;
}

まとめ

TypeScriptのリテラル型は、型安全性を高め、コードの品質を向上させる強力なツールです。適切に活用することで:

  • コンパイル時のエラー検出が可能
  • IDE上での補完機能の恩恵
  • コードの可読性と保守性の向上

が実現できます。実際のプロジェクトでは、APIの型定義やコンポーネントのプロパティ型など、様々な場面でリテラル型を活用することをお勧めします。