Search code examples
typescriptenums

Typescript Enum Object.values() return value


Why does Object.values() and Object.keys() always give both the keys and the values?

Consider the following code:

enum Enum {
    FOO,
    BAR
}

console.log(Object.values(Enum));
console.log(Object.keys(Enum));

The output of this would be:

[ 'FOO', 'BAR', 0, 1 ]
[ '0', '1', 'FOO', 'BAR' ]

Why does it do that and how do I only get the keys and values?


Solution

  • That's how enum types are transpiled by TypeScript.

    enum Enum {
        FOO,
        BAR
    }
    

    will become

    "use strict";
    var Enum;
    (function (Enum) {
        Enum[Enum["FOO"] = 0] = "FOO";
        Enum[Enum["BAR"] = 1] = "BAR";
    })(Enum || (Enum = {}));
    

    Notice that both numeric keys and string keys are provided for easy mapping to and from both types, enabling you to do something like this:

    const value = Enum.FOO;  // inferred type Enum.FOO
    const key = Enum[value]; // inferred type string
    

    If you want to get an array of only the numeric or string keys, you can do this:

    const numericKeys = Object.keys(Enum).map(x => parseInt(x)).filter(x => !isNaN(x));
    const stringKeys = Object.keys(Enum).filter(x => isNaN(parseInt(x)));
    

    Or for the numeric or string values (requires the es2017 library in your tsconfig):

    const numericValues = Object.values(Enum).filter(x => typeof x === "number");
    const stringValues = Object.values(Enum).filter(x => typeof x === "string");