TypeScriptのRecord型でキー値ペアを簡潔に管理

TypeScriptのRecord型でキー値ペアを簡潔に管理

TypeScriptのRecord型は、オブジェクトのキーと値の型を柔軟に指定し、データ構造を効率的に管理できる強力なユーティリティ型です。キーの型制約や値の型制約を活用することで、安全で直感的な型定義が可能になります。本記事では、Record型の基本構文から応用的な使用方法までを詳しく解説します。

Record型の基本構文

Record型は、`Record`という形式で定義され、キーの型を`K`、値の型を`T`として指定します。

type RecordExample = Record<string, number>;

const data: RecordExample = {
  key1: 100,
  key2: 200,
};

ユニオン型とRecord型

キーにユニオン型を指定することで、許可されたキーのみを持つオブジェクトを作成できます。

type Permissions = "read" | "write" | "execute";

type PermissionStatus = Record<Permissions, boolean>;

const status: PermissionStatus = {
  read: true,
  write: false,
  execute: true,
};

ジェネリックとRecord型

ジェネリックを用いることで、動的にキーと値の型を定義できます。

function createRecord<K extends string, T>(keys: K[], value: T): Record<K, T> {
  return keys.reduce((acc, key) => {
    acc[key] = value;
    return acc;
  }, {} as Record<K, T>);
}

const record = createRecord(["a", "b", "c"], 42);

型の再利用とRecord型

既存の型を再利用して、新しい型を生成できます。

type User = {
  id: number;
  name: string;
};

type ReadOnlyUser = Record<keyof User, string>;

const user: ReadOnlyUser = {
  id: "123",
  name: "Alice",
};

ネストされたRecord型

ネスト構造のデータを簡潔に表現できます。

type NestedRecord = Record<string, Record<string, number>>;

const nested: NestedRecord = {
  group1: {
    item1: 1,
    item2: 2,
  },
  group2: {
    item1: 3,
    item2: 4,
  },
};

Record型とユーティリティ型の併用

他のユーティリティ型と組み合わせることで、さらに柔軟な型定義が可能です。

type Config = Record<string, string>;

type OptionalConfig = Partial<Config>;

const config: OptionalConfig = {
  apiUrl: "https://api.example.com",
};

キーの型制約

Record型を使用することで、特定のキーのみを許容できます。

type FixedKeys = "name" | "age" | "email";

type UserProfile = Record<FixedKeys, string>;

const profile: UserProfile = {
  name: "John",
  age: "30",
  email: "john@example.com",
};

動的キーの生成

ジェネリックを使用して動的にキーを生成できます。

type DynamicKeys<T extends string> = Record<T, number>;

const dynamic: DynamicKeys<"x" | "y" | "z"> = {
  x: 10,
  y: 20,
  z: 30,
};

Record型のユースケース

設定オブジェクトやマッピングデータなど、多岐にわたる用途で使用されています。

// 設定の管理
type Config = Record<string, string>;

const appConfig: Config = {
  theme: "dark",
  language: "en",
};

型エラーの防止

Record型を使うことで、不正なキーや値の定義を防げます。

type AllowedKeys = "key1" | "key2";

type Data = Record<AllowedKeys, number>;

const data: Data = {
  key1: 100,
  key2: 200,
  // key3: 300, // エラー
};

Record型とデフォルト値

初期値を設定するパターンにも対応できます。

type DefaultedRecord<K extends string, T> = Record<K, T>;

const defaulted: DefaultedRecord<"a" | "b" | "c", number> = {
  a: 0,
  b: 0,
  c: 0,
};

まとめ

Record型は、型安全なキーと値のマッピングを実現する便利なツールです。ユニオン型やジェネリック、他のユーティリティ型と組み合わせることで、より強力で柔軟な型定義が可能になります。多様なデータ構造に対応できるRecord型を活用して、コードの保守性と可読性を向上させましょう。