Search⌘ K
AI Features

Enums

Explore TypeScript enums to define human-readable names for numeric or string values. Understand standard enums, string enums, and const enums, and how they help eliminate magic numbers while improving code clarity and performance.

Introduction to enums

Enums are a special type whose concept is similar to other languages, such as C#, C++, or Java, and provides the solution to the problem of special numbers or special strings.

Enums are used to define a human-readable name for a specific number or string.

Consider the following code:

TypeScript 4.9.5
// Define an enum with the values 'Open' and 'Closed'
enum DoorState {
Open,
Closed
}
// Declare a function that takes an argument of type 'DoorState'
function checkDoorState(state: DoorState) {
// Print the enum value to the console
console.log(`enum value is : ${state}`);
// Use a switch statement to check the value of 'state'
switch (state) {
// If 'state' is 'Open', print a message to the console
case DoorState.Open:
console.log(`Door is open`);
break;
// If 'state' is 'Closed', print a message to the console
case DoorState.Closed:
console.log(`Door is closed`);
break;
}
}
Defining enum DoorState
  • We start by using the enum keyword to define an enum named DoorState on line 2. This enum has two possible values, either Open or Closed.

  • We then have a function named checkDoorState on lines 8–23 that has a single parameter named state of type DoorState. This means that the ...