David Cuccia David Cuccia - 4 months ago 29
TypeScript Question

How to programmatically enumerate an enum type in Typescript 0.9.5?

Say I have a TypeScript enum, MyEnum, as follows:

enum MyEnum {
First,
Second,
Third
}


What would be the best way in TypeScript 0.9.5 to produce an array of the enum values? Example:

var choices: MyEnum[]; // or Array<MyEnum>
choices = MyEnum.GetValues(); // plans for this?
choices = EnumEx.GetValues(MyEnum); // or, how to roll my own?

Answer

This is the JavaScript output of that enum:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["First"] = 0] = "First";
    MyEnum[MyEnum["Second"] = 1] = "Second";
    MyEnum[MyEnum["Third"] = 2] = "Third";
})(MyEnum || (MyEnum = {}));

Which is an object like this:

Object {
    0: "First",
    1: "Second",
    2: "Third",
    First: 0,
    Second: 1,
    Third: 2
}

Member Names

To get the enum member names, we can filter the object's values by anything that is a string:

const names = Object.keys(MyEnum).map(k => MyEnum[k]).filter(v => typeof v === "string");

Contains: ["First", "Second", "Third"]

Member Values

While to get the enum member values, we can filter the object's values by anything that is a number:

const values = Object.keys(MyEnum).map(k => MyEnum[k])
    .filter(v => typeof v === "number").map(Number);

Contains: [0, 1, 2]

Extension Class

I think the best way to do this is to create your own functions (ex. EnumEx.getNames(MyEnum)). You can't add a function to an enum.

class EnumEx {
    static getNamesAndValues(e: any) {
        return this.getNames(e).map(n => { return { name: n, value: e[n] as number }; });
    }

    static getNames(e: any) {
        return this.getObjValues(e).filter(v => typeof v === "string") as string[];
    }

    static getValues(e: any) {
        return this.getObjValues(e).filter(v => typeof v === "number") as number[];
    }

    private static getObjValues(e: any): (number | string)[] {
        return Object.keys(e).map(k => e[k]);
    }
}
Comments