An enum
(enumeration) is a feature of TypeScript that allows you to define a set of constant values under a single name.
If you want to learn more about Enumerations
check the Introduction to Programming Course read more
To define an enum, the enum
keyword is used followed by the name of the enum and a block of braces that contains the values of the enum
.
enum NombreEnum {
VALOR1,
VALOR2,
VALOR3
}
Let’s see it with an example,
enum Direccion {
Norte,
Sur,
Este,
Oeste
}
let direccionActual: Direccion = Direccion.Norte;
console.log(direccionActual); // Output: 0
console.log(Direccion[direccionActual]); // Output: Norte
In this example, Direccion
is an enum that defines four values: Norte
, Sur
, Este
, and Oeste
. The values of the enum are automatically assigned to integer numbers, starting from 0.
Numeric Enums
By default, enums in TypeScript are numeric. Each value in the enum is assigned to a number, starting from 0 and increasing by 1 for each subsequent value.
Customizing numeric values
You can customize the numeric values assigned to each member of the enum.
enum Estado {
Inactivo = 0,
Activo = 1,
Pausado = 2
}
let estadoActual: Estado = Estado.Activo;
console.log(estadoActual); // Output: 1
Automatic increment
If a specific numeric value is defined for a member of the enum, subsequent values will automatically increment from that value.
enum Semana {
Lunes = 1,
Martes,
Miercoles,
Jueves,
Viernes
}
console.log(Semana.Lunes); // Output: 1
console.log(Semana.Martes); // Output: 2
console.log(Semana.Viernes); // Output: 5
String Enums
In addition to numeric enums, TypeScript also allows defining string enums, where each member of the enum is assigned to a string.
enum Color {
Rojo = "Rojo",
Verde = "Verde",
Azul = "Azul"
}
let colorFavorito: Color = Color.Verde;
console.log(colorFavorito); // Output: Verde
In this example, Color
is a string enum that defines three values: Rojo
, Verde
, and Azul
.
Heterogeneous Enums
Although it is not a common practice (nor probably advisable 😅), TypeScript allows defining enums that mix numeric and string values.
enum Mixto {
No = 0,
Si = "Sí"
}
console.log(Mixto.No); // Output: 0
console.log(Mixto.Si); // Output: Sí
Practical Examples
Comparisons
Enums are useful for making clear and readable comparisons in code.
enum Respuesta {
No = 0,
Si = 1
}
function responder(respuesta: Respuesta): void {
if (respuesta === Respuesta.Si) {
console.log("Positive response.");
} else {
console.log("Negative response.");
}
}
responder(Respuesta.Si); // Output: Positive response.
Iterating over enums
You can iterate over the values of an enum using loops and the Object.keys
function.
enum Talla {
Pequeña,
Mediana,
Grande
}
for (let talla in Talla) {
if (isNaN(Number(talla))) {
console.log(talla); // Output: Pequeña, Mediana, Grande
}
}