Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Lehks Avatar asked May 08 '19 16:05

Lehks


People also ask

How do you find the value of an object in an enum?

To get the values of enum entries we can use name keys of enum object as shown below. Or we can directly get names of enum object using Object. keys() method.

How do I get all the enum values in TypeScript?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.

Can enum value be object?

An enum is a data type that can be created by a Java programmer to represent a small collection of possible values. Technically, an enum is a class and its possible values are objects. Enums will be our first example of adding a new type to the Java language.

Can enum string value?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.


1 Answers

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");
like image 175
p.s.w.g Avatar answered Sep 19 '22 15:09

p.s.w.g