prmph prmph - 2 months ago 23
TypeScript Question

Typescript has unions, so are enums redundant?

Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:

enum X { A, B, C }
var x:X = X.A;

and a similar union type declaration:

type X: "A" | "B" | "C"
var x:X = "A";

If they basically serve the same purpose, and unions are more powerful and expressive, then why are enums necessary?


As far as I see they are not, due to the very simple reason. Union types are purely compile time concept, whereas enums are actually transpiled and end up in the resulting javascript (sample).

This allows you to do some things with enums, that are otherwise impossible with union types (like enumerating the possible enum values)