Getting values from Typescript enum with strings

typescript string enum, reverse mapping
typescript enum with multiple values
javascript enum get key by value
typescript enum to array
typescript enum in class
export enum typescript
typescript extend enum
typescript keyof enum

I am trying to get the values out of this enum:

enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}

With the following code as suggested in other StackOverflows, I get the following output:

var text=""
for (var size in Sizes) {
    text = text + "\n" + size;
}

console.log(text);

Tiny
VerySmall
Very Small
Small
Medium
Large
VeryLarge
Very Large

I do not want the entries VerySmall and VeryLarge, why are these appearing and how can I get my desired results?

Thanks!

It appears the typescript compiler being used is pre-2.4 where they added string value support in enums. Usually there's a reverse mapping from values to enums and values are generally numbers. But if you attempt to use strings prior to 2.4, the compiler wouldn't know what to do about it (and would actually produce errors) but will still generate the source.

Compare 2.4:

var Sizes;
(function (Sizes) {
    Sizes["Tiny"] = "Tiny";
    Sizes["VerySmall"] = "Very Small";
    Sizes["Small"] = "Small";
    Sizes["Medium"] = "Medium";
    Sizes["Large"] = "Large";
    Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));

To 2.3:

var Sizes;
(function (Sizes) {
    Sizes[Sizes["Tiny"] = "Tiny"] = "Tiny";
    Sizes[Sizes["VerySmall"] = "Very Small"] = "VerySmall";
    Sizes[Sizes["Small"] = "Small"] = "Small";
    Sizes[Sizes["Medium"] = "Medium"] = "Medium";
    Sizes[Sizes["Large"] = "Large"] = "Large";
    Sizes[Sizes["VeryLarge"] = "Very Large"] = "VeryLarge";
})(Sizes || (Sizes = {}));

And 2.3 without string values:

var Sizes;
(function (Sizes) {
    Sizes[Sizes["Tiny"] = 0] = "Tiny";
    Sizes[Sizes["VerySmall"] = 1] = "VerySmall";
    Sizes[Sizes["Small"] = 2] = "Small";
    Sizes[Sizes["Medium"] = 3] = "Medium";
    Sizes[Sizes["Large"] = 4] = "Large";
    Sizes[Sizes["VeryLarge"] = 5] = "VeryLarge";
})(Sizes || (Sizes = {}));

If you wanted to force that reverse mapping in 2.4 and up, you could assert the values to any.

enum Sizes {
  Tiny = <any>"Tiny",
  VerySmall = <any>"Very Small",
  Small = <any>"Small",
  Medium = <any>"Medium",
  Large = <any>"Large",
  VeryLarge = <any>"Very Large"
}

Just call it a feature.

String enums, TypeScript provides both numeric and string-based enums. numeric enums members also get a reverse mapping from enum values to enum names. As you see enum object is used to store two types of values - one type stores index and enum strings, other type stores reverse of data like string and enum. By default, each enum constants is assigned with numbers starting from 0,1 ie. Sunday=0, Saturday=1 defined enumeration with initializing string values

You can use Object.keys to get the enum keys and log the values, like this:

enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}

for (const size of Object.keys(Sizes)) {
    console.log(Sizes[size]);
}

Output:

Tiny
Very Small
Small
Medium
Large
Very Large

Transpiled example:

var Sizes;
(function (Sizes) {
    Sizes["Tiny"] = "Tiny";
    Sizes["VerySmall"] = "Very Small";
    Sizes["Small"] = "Small";
    Sizes["Medium"] = "Medium";
    Sizes["Large"] = "Large";
    Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));
for (var _i = 0, _a = Object.keys(Sizes); _i < _a.length; _i++) {
    var size = _a[_i];
    console.log(Sizes[size]);
}

Using enums with string values in TypeScript? Consider string , We need to use the keys in order to retrieve the site's content, and mapping each Contentful key to an enum means tossing out all the dots and  TypeScript 2.4 implemented one of the most requested features: string enums, or, to be more precise, enums with string-valued members. It is now possible to assign a string value to an enum member: enum MediaTypes { JSON = "application/json", XML = "application/xml" } The string enum can be used like any other enum in TypeScript:

In TypeScrit

enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}
class Test {
  constructor() {
    let text = '';

    for (const key in Sizes) {
      if (Sizes.hasOwnProperty(key)) {
        text += Sizes[key] + '<br/>';
      }
    }
    console.log(text);

    text = '';
    Object.keys(Sizes).map(key => text += Sizes[key] + '<br/>');
    console.log(text);
  }
}
let t = new Test();

Remember that a for-In should have a if-Statement!

Both console.log(text), should output the same string.

Tiny<br/>Very Small<br/>Small<br/>Medium<br/>Large<br/>Very Large<br/>

If you log Sizes[size] to console after the for-In you will imagine what happens and why you get the values.

String Enums in TypeScript, TypeScript 2.4 implemented one of the most requested features: string enums, It is now possible to assign a string value to an enum member: While string enums don’t have auto-incrementing behavior, string enums have the benefit that they “serialize” well. In other words, if you were debugging and had to read the runtime value of a numeric enum, the value is often opaque - it doesn’t convey any useful meaning on its own (though reverse mapping can often help), string enums allow you to give a meaningful and readable value

Enum in TypeScript, In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values. There are three types  If you do Numbers.one you of course get the number 1. But let's say you have the enum value and you want to print it out. It's easy to get the string value by using an array indexer on the enum type. var myNumber = Numbers.two;

Writing readable code with TypeScript enums, allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values. The proposal is to create an enum that uses string values as opposed to the currently used numeric values. After TypeScript 2.1 was released, user wallverb posted an interesting solution leveraging the new features – many thanks for the inspiration.

Convert String to equivalent Enum value, called elements, members, enumeral, or enumerators of the type. Starting with TypeScript 0.9.7, accessing an enum value via a string got a little bit inconveniant. Before 0.9.7 you could do In 0.9.7, this will report "Index signature of object type implicitly has an 'any' type". According to Microsoft, this is intended behavior. At the moment, there are thre

Comments
  • Your for loop will print only keys, to get values, use Sizes[size].
  • Also the output you posted is not correct, it can't print both key and value at the same time with your logic.
  • @Deshak9 Here's the fiddle : jsfiddle.net/98o7cysv
  • It actually seems to be a TypeScript-Bug. Even the recommended way in the Microsoft docs leads to the same result.
  • You can check out the source too to see how it emits enums. 2.3 vs 2.4
  • This doesn't work as expected in the following example: jsfiddle.net/7jk6z3n2
  • No, forcing them to be any will cause this to happen in current versions. To fix your fiddle, you need to force a specific version of typescript to be used (which doesn't seem to be possible).
  • jsfiddle uses version typescript version 1.7.3, which does not support string values for enums. See for yourself, look for the ts.version.
  • Try out here TypeScriptPlayground I test it and it works, but remove the 'export' before 'class'