Skip to content

Typescript: Understanding enums

Jan 20, 2020

TypeScript is a programming language that is widely used for developing web applications. It is a superset of JavaScript that offers several additional features, including support for enums. In this article, we will introduce you to TypeScript enums, explain what they are, and show you how to use them in your code.

What is an enum?

An enum is a data type that allows you to define a set of named values. It is a collection of related constants that can be accessed using their names instead of their values. In TypeScript, enums are implemented as a set of named values that are associated with numeric or string values.

Declaring an enum

To declare an enum in TypeScript, you use the enum keyword followed by the name of the enum. Here’s an example of how to declare an enum called Direction:

Copy code
enum Direction {
  Up,
  Down,
  Left,
  Right,
}

In this example, we have defined a Direction enum with four named values: Up, Down, Left, and Right. By default, the values of the named values start at 0 and increment by 1. So, Up has a value of 0, Down has a value of 1, Left has a value of 2, and Right has a value of 3.

Accessing enum values

You can access the values of an enum using the dot notation. Here’s an example of how to access the values of the Direction enum we defined earlier:

Copy code
const up = Direction.Up; // up === 0
const down = Direction.Down; // down === 1
const left = Direction.Left; // left === 2
const right = Direction.Right; // right === 3