Enums is a special type whose concept will already be familiar to you if you come from languages like C#, C++, Java, etc.
Enums are used to define a human-readable name for numbers or strings with specific meaning.
This is how you declare an enums in TypeScript:
Now, let’s look at how we can use this enums.
So, we start by declaring an enum called
ModalState. This enum has two possible values,
Closed. We then created a function called
checkModalState that take a single argument called
state of type
ModalState. This means that we can only call this function with one of the values of the
The function logs the actual value of the
state parameter to the console then executes a
switch statement. The
switch statements logs a message to the console depending on the value of the
state parameter we passed in.
Let’s run the function with the following code.
The output of this code is as follows:
As you can see, the TypeScript compiler has generated a numerical value for all the values in our enum. The value for
0, and the value for
Enums eliminates the so called magic numbers by defining a clear possible values. Enums helps us provide a clear set of values for a variable or function parameter. Like in the example above, we can only pass
ModalState.Closed to our function.
We can also set the numerical value of an enum to whatever we like. For example:
Now, if we run the
checkModalState function again.
We’ll get the following output:
In TypeScript, we are not limited to numeric enums. We can also use a string enum. Let’s look at an example.
console.log() the value.
As expected, TypeScript compiler is resolving the enum value to the
String enums don’t auto-increment like the numeric enum. You’ve got to assign a value to all the other enum values the moment you assign a value to one.
You can also make a heterogenous enums like this, but it’s generally not recommended.
String enum is particularly useful when we’re debugging. Unlike the runtime value of numeric enums, the value of string enums convey a meaningful and readable value that’ll make our debugging experience much better.
When requirements are tight, and our code has to be as minimal as possible, we can use the const enums by adding the
const keyword before the enum definition.
Const enum is introduced for performance reasons. The enums are completely removed during compilation.
This is how the code above look like after compilation.
Now, back to const enum. No object is generated at all. They are completely removed during compilation.
TypeScript will make this kind of complain if we try to
console.log() const enum.
That’s understandable because
Result of compilation:
That’s it for the basic of the TypeScript enums. Of course there’re still lots of detail that you can read on the official docs if you want to understand TypeScript enums even more.