DEV Community

Discussion on: We don't have to use Enums on TypeScript? 【Discussion】

Collapse
 
nikolaymatrosov profile image
Nikolay Matrosov

Have you heard about const enum? It transplies to values only. E.g.

const enum Test {
    FOO = 'foo',
    BAR = 'bar'
}

const s = Test.BAR;
Enter fullscreen mode Exit fullscreen mode

results in

const s = "bar" /* BAR */;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pontakornth profile image
Pontakorn Paesaeng

I think it's neat. ReScript also uses this approach. Also, you need a plugin if you use Babel.

Collapse
 
taishi profile image
Taishi

This is cool. I just prefer Union types but this is great if this Enums gets stripped out when compiling! Thanks @nikolaymatrosov !

Collapse
 
firstwhack profile image
FirstWhack • Edited

You can't index a union type unless you're creating a lookup table based on the union so "prefer unions" is simply unviable. This is what TS does but TS can remove that lookup at compile time for "const" Enums.

Don't reinvent core features.