Does TypeScript fail at enums?

Alex Lohr - Jul 4 - - Dev Community

The concept of enumerables is quite simple: an item that can represent a finite number of different things. However, the implementation in languages are very different. Some languages like Rust and F# allow enum branches to be containers other types. Most of them compile away the enums to simple numbers without leaving a trace of their use in the compiled code. TypeScript... doesn't really do well in comparison.

Consider the following enum:

enum EnumImplementations {
  Rust,
  FSharp,
  TypeScript,
}

console.log(EnumImplementation.TypeScript);
Enter fullscreen mode Exit fullscreen mode

Transpilation to JavaScript will yield the following result:

var EnumImplementations;
(function (EnumImplementations) {
    EnumImplementations[EnumImplementations["Rust"] = 0] = "Rust";
    EnumImplementations[EnumImplementations["FSharp"] = 1] = "FSharp";
    EnumImplementations[EnumImplementations["TypeScript"] = 2] = "TypeScript";
})(EnumImplementations || (EnumImplementations = {}));

console.log(EnumImplementation.TypeScript);
Enter fullscreen mode Exit fullscreen mode

This is a lot of complex code just to give more meaning to three numbers. Even worse, many tree shaking strategies will leave it as is.

What we would actually need for TypeScript to emit (used JSDoc for the type definition):

/**
 * enum EnumImplementation
 * @typedef {(typeof _EnumImplementation_Rust | typeof _EnumImplementation_FSharp | typeof _EnumImplementation_TypeScript)} EnumImplementation
 */
const _EnumImplementation_Rust = 0;
const _EnumImplementation_FSharp = 1;
const _EnumImplementation_TypeScript = 2;
const _EnumImplementation_Keys = ["Rust", "FSharp", "TypeScript"];

console.log(_EnumImplementations_TypeScript);
Enter fullscreen mode Exit fullscreen mode

Not only has that the advantage of being easily tree-shakable, it is also more readable and concise.

That was a long rant, sorry. What's your take on the issue?

Disclaimer: please don't misunderstand me, I really like TypeScript, but this is one of its shortcomings that rather irks me.

. . . . . . . . . . . . . . . . . . . . .
Terabox Video Player