-
Notifications
You must be signed in to change notification settings - Fork 5
Spaghetti enums in JavaScript
Lóránt Pintér edited this page Feb 12, 2015
·
5 revisions
Enums are awesome features of many languages. However, each language has its own idea about how to represent enums in JavaScript:
- Haxe stores them as arrays with name and index:
MyEnum.Alma = ["Alma", 0];
- TypeScript has a strange way:
MyEnum[MyEnum["Alma"] = 0] = "Alma";
- Kotlin uses objects in place of integers:
{ Alma: new _.MyEnum() }
- etc.
Converting between these enum representations when an object passes the barrier between, say, a Haxe and a TypeScript module would be pretty complicated. It would also impact the performance of the code.
Instead, Spaghetti uses simple integers in place of enum values, and tries to do its best to retain as much type-safety and convenience as it is possible with the given language.
- In Haxe, Spaghetti generates an abstract type that almost completely emulates a native enum type,
- In TypeScript we can actually use the real enums, as the values are passed around as simple numbers,
- In Kotlin we generate the same, but within a class object.