389

What is the proper way to loop through literals of an enum in TypeScript?

(I am currently using TypeScript 1.8.1.)

I've got the following enum:

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);
        }
    }

The result displayed is a list

0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre

I do want only four iterations in the loop as there are only four elements in the enum. I don't want to have 0 1 2 and 3 that seem to be index numbers of the enum.

1

1 Answer 1

642

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)


Edit

String enums look different than regular ones, for example:

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 just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)
14
  • 4
    It doesn't work because 0 1 2 3 are strings. Sep 7, 2016 at 14:46
  • 5
    That's why there's a check for isNaN(Number(...)). It works in the playground I shared Sep 7, 2016 at 15:01
  • 10
    Thanks for this approach. For the Object.keys method, you'll want to use Object.keys(MotifIntervention).filter(key => isNaN(Number(key))). Feb 13, 2018 at 17:56
  • 8
    This doesn’t work if you're expecting to loop through values of the enum type. So for (let item in MotifIntervention) { doThing(item) } will fail if typeof doThing function is (arg: MotifIntervention) => void. That's because the for..in loop will treat item as type string, not type MotifIntervention.
    – chharvey
    Sep 24, 2018 at 18:00
  • 8
    @NitzanTomer - that sounds like a good workaround at runtime, but i'm talking about compile time. When you attempt to call doThing(item) and doThing is of type (arg: MotifIntervention) => void, you'll get a compile time error "Argument of type 'string' is not assignable to parameter of type 'MotifIntervention'."
    – chharvey
    Sep 24, 2018 at 19:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.