DEV Community

Discussion on: Managing Key-Value Constants in TypeScript

Collapse
 
michaeljota profile image
Michael De Abreu • Edited

What is advantage between this and a string enum?

export enum Colors {
  blue = 'Blue',
  green = 'Green',
  red = 'Red',
}
Enter fullscreen mode Exit fullscreen mode

String enums are transformed to regular objects, so you could access them as Colors.blue, just like in your example.

Collapse
 
hinogi profile image
Stefan Schneider

I had an example just now :D

Image description

Collapse
 
michaeljota profile image
Michael De Abreu

Please check the playground link. String enums are just regular objects. You can see in the output of the Playground.
typescriptlang.org/play?#code/KYOw...

Collapse
 
lacolaco profile image
Suguru Inatomi

As far as I know, there isn't an advantage technically. But I prefer union types because enum is not an ECMAScript's standard syntax.
After transpilation, output code with a tuple and an object is similar to the original TS code, but output code with enum is different from the original TS code a lot.
I think a big value of TypeScript is the mindset; it is a superset of ECMAScript. So I don't want to use enum.

Collapse
 
michaeljota profile image
Michael De Abreu

As long as you know what it becomes, I always suggest the usage of the languages features. Whatever they are.

Collapse
 
woodywoodsta profile image
Sean Wood

I hear what you're saying! But that's similar to buying a bigger car and never putting anything in the extra space because it wasn't available in your standard car.

I think that the choice of adopting Typescript as a language comes with the acceptance of a build step, the outcome of which is up to the compiler.