Help us understand the problem. What is going on with this article?

TypeScriptの文字列enumでrawValue→enumを実現する

More than 1 year has passed since last update.

TypeScriptの仕様上、文字列enumはreverse mapping(rawValue→enum)ができません
(文字列の場合、生の値が重複する可能性があるから・・・?)。
実際に公式のドキュメントにも記述があります。(https://www.typescriptlang.org/docs/handbook/enums.html)

Keep in mind that string enum members do not get a reverse mapping generated at all.

仕組みがないなら作ってしまおうということで、ヘルパーメソッド的なものを自作してみました。v3.1.6で動作確認しています。

export function mapToEnum<T>(enumObject: T, value: any): T[keyof T] | undefined {
  if (typeof enumObject === 'object') {
    for (const key in enumObject) {
      if (enumObject.hasOwnProperty(key) && enumObject[key] === value) {
        return enumObject[key]
      }
    }
  } else if (enumObject instanceof Array) {
    return enumObject.find(value)
  }
  /* 3.0.x
  } else if ((enumObject as any) instanceof Array) {
    return (enumObject as any[]).find(value)
  }
  */
}

////////////////////

enum Meta {
  Hoge = 'hoge',
  Fuga = 'fuga',
  Foo = 'foo',
  Bar = 'bar'
}

const meta: Meta = mapToEnum(Meta, 'hoge')
console.log(meta) // hoge

本当はenumに存在する文字列だけ受け取れるようにしたいところですが、それができなかったので戻り値でundefinedを許容するようにしました。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away