Enums, short for enumerations, are a powerful feature in TypeScript that allow developers to define a set of named constants. They provide a way to create a collection of related values that can be used as distinct types.
To define an enum in TypeScript, use the enum
keyword followed by the enum name and a set of comma-separated members:
enum Direction {
North,
East,
South,
West
}
By default, enums are number-based, starting from 0. You can also assign custom values to enum members:
enum HttpStatus {
OK = 200,
NotFound = 404,
InternalServerError = 500
}
TypeScript also supports string enums, which are more readable and debuggable:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
Enums can be used as types and accessed using dot notation:
let myDirection: Direction = Direction.North;
console.log(myDirection); // Output: 0
let statusCode: HttpStatus = HttpStatus.OK;
console.log(statusCode); // Output: 200
let favoriteColor: Color = Color.Blue;
console.log(favoriteColor); // Output: "BLUE"
Numeric enums support reverse mapping, allowing you to get the enum member name from its value:
console.log(Direction[0]); // Output: "North"
console.log(HttpStatus[404]); // Output: "NotFound"
For better performance, you can use const enums. These are erased during compilation and inlined at use sites:
const enum Planet {
Earth,
Mars,
Jupiter
}
let myPlanet = Planet.Earth; // Compiles to: let myPlanet = 0;
To further enhance your TypeScript skills, explore these related topics:
Enums in TypeScript provide a powerful way to define a set of named constants, improving code readability and maintainability. By understanding their syntax and best practices, you can effectively use enums in your TypeScript projects.