Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from Typescript enum with strings

Tags:

typescript

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!

like image 976
user82395214 Avatar asked Sep 04 '26 21:09

user82395214


1 Answers

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.

like image 126
Jeff Mercado Avatar answered Sep 07 '26 15:09

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!