Learn TypeScript

Creating enums

Creating enums

In this lesson, we will learn how to create enumeration types.

What is an enumeration?

An enumeration is a type that represents named constants and is often referred to as an enum. If the meaning of the constant's value is not apparent, it can make code easier to understand.

Consider the example below:

if (status === 5) {
// do something
}
if (status === JobStatus.Completed) {
// do something
}

The second if statement is easier to understand than the first if statement.

Enum syntax

The enum syntax is as follows:

enum TypeName {
value1,
value2,
...
}

The type name follows the enum keyword. The value names are then listed inside curly brackets.

Numeric enums

We are going to explore enums in an exercise.

TypeScriptOpen exercise in CodeSandbox
  • Create an enum type called Level containing names High, Medium, and Low.
🤔

What values correspond to the enum names? Discover what they are by outputting them to the console

enum values are zero-based auto-incrementing numbers by default.

  • Set the level variable to 5.
level = 5;
🤔

Does a type error occur?

String enums

Enum values can be string's if we explicitly define a string value after the name. For example:

enum Day {
Monday = 'MON',
Tuesday = 'TUE',
Sunday = 'WED',
...
}
  • Update the Level enum so that the values for Level.High, Level.Medium, and Level.Low are "H", "M" and "L" respectively.
  • Set the level variable to "VH"
level = "VH";
🤔

Does a type error occur?

  • Set the level variable to "H"
level = "H";
🤔

Does a type error occur?

  • Set the level variable to Level.High:
level = Level.High;
🤔

Does a type error occur?

String enum values are strongly-typed to the named values declared in the enum.

Nice!

Summary

Enums are a type that can make code more readable, where the meaning of a value of a variable is not apparent.

Well done!

In the next lesson, we will learn how to strongly-type objects.

© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more