Problem
In TypeScript, how do you loop through the literals of an enum?
(I’m using TypeScript 1.8.1 right now.)
The following enum is what I have:
export enum MotifIntervention {
Intrusion,
Identification,
AbsenceTest,
Autre
}
export class InterventionDetails implements OnInit
{
constructor(private interService: InterventionService)
{
let i:number = 0;
for (let motif in MotifIntervention) {
console.log(motif);
}
}
A list is displayed as a result.
0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre
Because there are only four members in the enum, I only want four iterations in the loop. I don’t want 0 1, 2, or 3 to appear as the enum’s index numbers.
Asked by Anthony Brenelière
Solution #1
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(code in playground)
String enums, for example, differ from normal enums in appearance:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which simply gives you the following object:
{
A: "a",
B: "b",
C: "c"
}
All the keys ([“A”, “B”, “C”]) can be obtained in the following manner:
Object.keys(MyEnum);
The values ([“a”, “b”, “c”]) are as follows:
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
Answered by Nitzan Tomer
Post is based on https://stackoverflow.com/questions/39372804/how-can-i-loop-through-enum-values-for-display-in-radio-buttons