TypeScript enum の逆マッピング: キーを値から取得する 4 つの方法

2024-06-08

TypeScript で enum のキーを値文字列で取得する方法(逆マッピング)

手動による for-in ループ

最も基本的な方法は、for-in ループを使用して、enum の各メンバーを反復し、値を比較することです。

enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 'blue'
}

function getEnumKeyByValue(value: string): string | undefined {
  for (const key in Color) {
    if (Color[key] === value) {
      return key;
    }
  }
  return undefined;
}

const colorValue = 'green';
const colorKey = getEnumKeyByValue(colorValue);
console.log(colorKey); // Output: Green

Object.keys()Object.values() を組み合わせて、enum のキーと値の配列を取得し、値を比較する方法もあります。

enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 'blue'
}

function getEnumKeyByValue(value: string): string | undefined {
  const enumKeys = Object.keys(Color);
  const enumValues = Object.values(Color);

  for (let i = 0; i < enumValues.length; i++) {
    if (enumValues[i] === value) {
      return enumKeys[i];
    }
  }
  return undefined;
}

const colorValue = 'green';
const colorKey = getEnumKeyByValue(colorValue);
console.log(colorKey); // Output: Green

valueOf メソッドの使用(数値型 enum のみ)

数値型の enum では、valueOf メソッドを使用して、値からキーを取得することができます。

enum Color {
  Red = 0,
  Green = 1,
  Blue = 2
}

function getEnumKeyByValue(value: number): keyof typeof Color | undefined {
  return Object.keys(Color).find(key => Color[key] === value);
}

const colorValue = 1;
const colorKey = getEnumKeyByValue(colorValue);
console.log(colorKey); // Output: Green

逆引きマップの作成

enum のメンバーごとに、値とキーのマッピングを格納した逆引きマップを作成する方法もあります。

enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 'blue'
}

const colorValueToKeyMap: { [value: string]: keyof typeof Color } = {
  red: 'Red',
  green: 'Green',
  blue: 'Blue'
};

function getEnumKeyByValue(value: string): keyof typeof Color | undefined {
  return colorValueToKeyMap[value];
}

const colorValue = 'green';
const colorKey = getEnumKeyByValue(colorValue);
console.log(colorKey); // Output: Green

注意事項

  • 上記の方法は、いずれも パフォーマンス上のオーバーヘッド が発生する可能性があります。頻繁に逆マッピングを行う場合は、パフォーマンスを考慮する必要があります。
  • TypeScript 4.0 以降では、enum にジェネリック型パラメータを指定できるようになりました。これにより、型安全な逆マッピング を実装することが可能になっています。

    以上、TypeScript で enum のキーを値文字列で取得する方法(逆マッピング)について解説しました。




    TypeScript で enum のキーを値文字列で取得する方法(逆マッピング) - サンプルコード

    手動による for-in ループ

    enum Color {
      Red = 'red',
      Green = 'green',
      Blue = 'blue'
    }
    
    function getEnumKeyByValue(value: string): string | undefined {
      for (const key in Color) {
        if (Color[key] === value) {
          return key;
        }
      }
      return undefined;
    }
    
    const colorValue = 'green';
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    

    Object.keys() と Object.values() の組み合わせ

    enum Color {
      Red = 'red',
      Green = 'green',
      Blue = 'blue'
    }
    
    function getEnumKeyByValue(value: string): string | undefined {
      const enumKeys = Object.keys(Color);
      const enumValues = Object.values(Color);
    
      for (let i = 0; i < enumValues.length; i++) {
        if (enumValues[i] === value) {
          return enumKeys[i];
        }
      }
      return undefined;
    }
    
    const colorValue = 'green';
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    

    valueOf メソッドの使用(数値型 enum のみ)

    enum Color {
      Red = 0,
      Green = 1,
      Blue = 2
    }
    
    function getEnumKeyByValue(value: number): keyof typeof Color | undefined {
      return Object.keys(Color).find(key => Color[key] === value);
    }
    
    const colorValue = 1;
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    

    逆引きマップの作成

    enum Color {
      Red = 'red',
      Green = 'green',
      Blue = 'blue'
    }
    
    const colorValueToKeyMap: { [value: string]: keyof typeof Color } = {
      red: 'Red',
      green: 'Green',
      blue: 'Blue'
    };
    
    function getEnumKeyByValue(value: string): keyof typeof Color | undefined {
      return colorValueToKeyMap[value];
    }
    
    const colorValue = 'green';
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    



    TypeScript で enum のキーを値文字列で取得する方法(逆マッピング) - その他の方法

    シンボル

    TypeScript 2.4 以降では、シンボルを使用して、型安全 な逆マッピングを実装することができます。

    enum Color {
      Red = Symbol('Red'),
      Green = Symbol('Green'),
      Blue = Symbol('Blue')
    }
    
    function getEnumKeyByValue(value: symbol): keyof typeof Color | undefined {
      return Object.keys(Color).find(key => Color[key] === value);
    }
    
    const colorValue = Color.Green;
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    

    Reflect API を使用して、enum のメンバーに関する情報を取得することもできます。

    enum Color {
      Red = 'red',
      Green = 'green',
      Blue = 'blue'
    }
    
    function getEnumKeyByValue(value: string): keyof typeof Color | undefined {
      const enumMembers = Reflect.ownKeys(Color);
      for (const key of enumMembers) {
        if (typeof key === 'string' && Color[key] === value) {
          return key;
        }
      }
      return undefined;
    }
    
    const colorValue = 'green';
    const colorKey = getEnumKeyByValue(colorValue);
    console.log(colorKey); // Output: Green
    

    ライブラリの利用

    ts-enum-util などのライブラリを使用すると、enum の操作をより簡単にユーティリティ関数として提供することができます。

    import { getEnumKeyByValue } from 'ts-enum-util';
    
    enum Color {
      Red = 'red',
      Green = 'green',
      Blue = 'blue'
    }
    
    const colorValue = 'green';
    const colorKey = getEnumKeyByValue(Color, colorValue);
    console.log(colorKey); // Output: Green
    
    • 上記の方法は、いずれも 複雑 な実装になる場合があり、理解メンテナンス が難しくなる可能性があります。
    • ライブラリを使用する場合は、ライブラリのドキュメント をしっかりと確認し、適切に 使用する必要があります。

    typescript


    TypeScriptでインターフェースを使いこなして、コードをもっと読みやすく、理解しやすいものにしよう!

    インターフェースを作成するまず、オブジェクトの構造を定義するインターフェースを作成します。インターフェースは、プロパティの名前と型を定義します。次に、Array<T>型を使用して、インターフェース型の配列を定義します。Tはインターフェースの名前です。...


    Angularで子コンポーネントにコールバック関数を渡す方法:bind(this)を使用する

    方法1:bind(this)を使用する親コンポーネントでコールバック関数を定義します。子コンポーネントのテンプレートで、bind(this)を使用して親コンポーネントのコールバック関数をバインドします。子コンポーネントで、@Inputデコレータを使用してコールバック関数をバインドします。...


    インターフェースとモデルを使いこなして、TypeScript/Angular開発をレベルアップ!

    TypeScript/Angular開発において、インターフェースとモデルは重要な役割を果たします。しかし、それぞれどのような役割を持ち、どのように使い分けるべきか悩むこともあるでしょう。インターフェースは、オブジェクトの構造を定義する型です。プロパティの名前と型を指定することで、オブジェクトがどのような属性を持つべきかを定義します。インターフェース自体はオブジェクトを作成できませんが、オブジェクトの型チェックや型推論に役立ちます。...


    Date オブジェクトを使いこなす

    Date オブジェクトのメソッドを使うDate オブジェクトには、日付と時刻をフォーマットするための様々なメソッドが用意されています。 例えば、以下のようにして、現在の日付を "yyyy年MM月dd日 HH時mm分ss秒" の形式でフォーマットすることができます。...


    React + TypeScript + JSONデータ - 型エラー「Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes'」を解決してデータを読み込む

    reactjsとtypescriptで開発している際に、jsonデータをreactコンポーネントに読み込んで使用しようとすると、Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes'というエラーが発生することがあります。...


    SQL SQL SQL SQL Amazon で見る



    TypeScriptでEnumを使いこなす:キーと値の取得・操作のベストプラクティス

    typeof 演算子を使用するTypeScript 2.4 以降では、typeof 演算子を使用して Enum からキーを取得することができます。これは、次のような構文で実現できます。この方法では、typeof 演算子を使用して Enum 型そのものを取得し、そのインデクサブル型を利用して、値をキーとしてアクセスします。