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 redundant, due to the very simple reason that union types are purely a 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)
Enums can be seen conceptually as a subset of union types, dedicated to
int
and/orstring
values, with a few additional features mentioned in other responses that make them friendly to use.But enums are not totally safe:
Union types support heterogenous data and structures, enabling polymorphism for instance:
In between enums and union types, singletons can replace enums. It's more verbose but also more object-oriented:
I tend to look at F# to see good modeling practices. A quote from an article on F# enums on F# for fun and profit that can be useful here:
There are few reasons you might want to use an
enum
enum
.enum
asflags
. Bit FlagsI see the big advantages of using a union is that they provide a succinct way to represent a value with multiple types and they are very readable.
let x: number | string
EDIT: As of TypeScript 2.4 Enums now support strings.