typescript-enums

Using Enums in TypeScript

  • 3 min

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
}
Copied!

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
Copied!

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
Copied!

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
Copied!

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
Copied!

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í
Copied!

Practical Examples