Typescript Enum Object.values() return value
15,770
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");
Related videos on Youtube
Author by
Lehks
Some guy. Likes programming, food and sleep. Pretty much in that order.
Updated on September 14, 2022Comments
-
Lehks over 1 year
Why does
Object.values()
andObject.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?
-
Aleksey L. almost 5 yearsMore info on enums: stackoverflow.com/questions/28818849/…. How to get keys/values: github.com/Microsoft/TypeScript/issues/…
-
-
Lehks almost 5 yearsOkay, thank you very much. Is there a way to only get the values then? I suppose it would be possible to get that result by using Array.splice() but I am not sure if the order is always the same (although it seems that way).
-
Aleksey L. almost 5 years
const values = Object.values(Enum).filter(v => typeof v === 'number');