TypeScript supports 2 types of enums:
- Numeric enums
- String enums
From the documentation:
Numeric enums
An enum can be defined using the
enum
keyword.enum Direction { Up = 1, Down, Left, Right, }
Above, we have a numeric enum where
Up
is initialized with1
. All of the following members are auto-incremented from that point on. In other words,Direction.Up
has the value1
,Down
has2
,Left
has3
, andRight
has4
.Numeric enums can be mixed in computed and constant members (see below).
String enums
String enums are a similar concept, but have some subtle runtime differences as documented below. In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT", }
While string enums don’t have auto-incrementing behavior, string enums have the benefit that they “serialize” well. In other words, if you were debugging and had to read the runtime value of a numeric enum, the value is often opaque - it doesn’t convey any useful meaning on its own (though reverse mapping can often help), string enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself.
In my situation I was using a Numeric enum but I wanted to display the related name on the screen(in my situation a Status value):
To display this value in a View I had to use some extra magic:
- First I had to import the enum in the corresponding component file:
- Next step was to create a public property on the component class that exposes this type:
- Now I can access this property on my view and get the enum string value: