Enums in TypeScript provide a way to define a set of named constants, making code easier to read and understand. They’re especially useful when you need a collection of related values that won’t change, such as days of the week or status codes. This guide covers everything you need to know about TypeScript enums, from basic syntax to advanced usage and real-world applications.
Enums (short for “enumerations”) in TypeScript provide a way to define named constants, creating a type-safe way to work with a fixed set of values. Enums can represent both numeric and string values, giving you flexibility in how they are used. This guide will walk you through everything from the basics to advanced applications, making it easy to integrate enums into your TypeScript projects.
An enum is a way to create a collection of related values, each with its own name. Enums in TypeScript can be of two types: numeric and string. They allow you to use friendly names to refer to fixed values, making your code easier to read and reducing errors caused by using “magic numbers” or strings.
enum Status {
Pending,
InProgress,
Completed
}
In this example:
Enums in TypeScript can be declared in two ways: as numeric enums and as string enums.
Numeric enums are the default in TypeScript. When you declare a numeric enum, each member is assigned a numeric value starting from 0 by default, and each subsequent member’s value is incremented by 1.
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
console.log(Direction.Up); // Output: 0
console.log(Direction.Right); // Output: 3
In this example:
You can assign custom values to enum members, and TypeScript will continue incrementing from the specified value.
enum Role {
Admin = 1,
User = 5,
Guest // 6 (incremented automatically)
}
console.log(Role.Admin); // Output: 1
console.log(Role.Guest); // Output: 6
Here:
String enums allow you to assign meaningful names as values to the enum members instead of numeric values. This is useful when the values themselves convey information.
enum Status {
Pending = "PENDING",
InProgress = "IN_PROGRESS",
Completed = "COMPLETED"
}
console.log(Status.Pending); // Output: PENDING
In this example:
You can access enum values and keys in TypeScript using dot notation. TypeScript enums are bi-directional for numeric enums, meaning you can get the name of an enum by its value and vice versa.
enum Days {
Monday,
Tuesday,
Wednesday
}
console.log(Days.Monday); // Output: 0
console.log(Days.Tuesday); // Output: 1
With numeric enums, you can use the value to get the key.