Enums は、一意の識別子の番号ベースのコレクションの編成を可能にするTypeSciptデータ型です。
単純な列挙型を定義する方法は次のとおりです。
enum Transport {
train,
bus,
bike,
car
}
let myTransport = Transport.bus;
console.log(myTransport); // 1
列挙値には、その数値またはそれに関連付けられている文字列によってアクセスできます。
enum Students {
Ann,
Bob,
John,
Zed
}
console.log(Students['John']); // 2
console.log(Students[3]); // Zed
列挙型はゼロベースですが、最初の項目に選択した数値を設定することで変更できます。 たとえば、列挙型には1で始まるインデックスがあります。
enum Tools {
hammer = 1,
screwdriver,
saw,
wrench
}
console.log(Tools.saw); // 3
または、新しい値にスキップすると、次の値が続きます。
enum Tools {
hammer,
screwdriver,
saw = 100,
wrench
}
console.log(Tools.wrench); // 101
このため、異なるファイルの列挙型に追加し、同じ列挙型に追加し続けることができます。
enum Sports {
Soccer,
Football,
Basketball,
}
// ...
// Later or in another file:
enum Sports {
Swimming = 3,
Running,
Hockey
}
列挙型は単純なJavaScriptオブジェクトになり、 JSON.stringify を呼び出すことで、上記のSports列挙型の結果オブジェクトは次のようになります。
console.log(JSON.stringify(Sports, null, '\t'));
{
"0": "Soccer",
"1": "Football",
"2": "Basketball",
"3": "Swimming",
"4": "Running",
"5": "Hockey",
"Soccer": 0,
"Football": 1,
"Basketball": 2,
"Swimming": 3,
"Running": 4,
"Hockey": 5
}