An 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, check out the Introduction to Programming Course
To define an enum, use the keyword enum followed by the enum name and a block of curly braces containing the enum values.
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, Direction is an enum that defines four values: North, South, East, and West. The enum values are automatically assigned integer numbers, starting from 0.
Numeric Enums
By default, enums in TypeScript are numeric. Each value in the enum is assigned 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 enum member.
enum Estado {
Inactivo = 0,
Activo = 1,
Pausado = 2
}
let estadoActual: Estado = Estado.Activo;
console.log(estadoActual); // Output: 1
Automatic increment
If you define an explicit numeric value for an enum member, the 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 enum member is assigned a text 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: Red, Green, and Blue.
Heterogeneous Enums
Although not a common practice (and probably not 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 performing 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
}
}
