37
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptのEnumのループはObject.entries()で実現可能

Posted at

TypeScriptのEnumはObject.entries()でループが可能だったのでメモ。

EnumはJSでどのように表示されるか

export enum Hoge {
  FOO,
  BAR,
  PIYO
}

というEnumを記述すると、以下のようなJSにトランスパイルされる。

export var Hoge;
(function (Hoge) {
    Hoge[Hoge["FOO"] = 0] = "FOO";
    Hoge[Hoge["BAR"] = 1] = "BAR";
    Hoge[Hoge["PIYO"] = 2] = "PIYO";
})(Hoge || (Hoge = {}));

早い話がJS内ではオブジェクトに変換されているということなので、Object.entries()を使えば要素ごとのループが可能ということがわかる。ということで、

Object.entries(Hoge).forEach(([key, value]) => {
  console.log(key, value)
})

/*
0 FOO
1 BAR
2 PIYO
と出力
*/


と書けばOK。

37
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?