Sub topic 2
Numeric Enums
Assume you know basic TypeScript types, functions, object literals, and switch statements. This chapter compares numeric and string enums and shows their JavaScript runtime output.
Numeric enums
A numeric enum defines named constants backed by numbers. When no values are provided, members start at 0 and increase by one.
enum Level {
Low,
Medium,
High,
}
function describe(level: Level): string {
switch (level) {
case Level.Low:
return "Low priority";
case Level.Medium:
return "Medium priority";
case Level.High:
return "High priority";
}
}
console.log(Level.Medium); // 1
console.log(describe(Level.High)); // High priorityYou can assign a starting value or explicit values:
enum HttpStatus {
Ok = 200,
NotFound = 404,
ServerError = 500,
}Numeric enums have a reverse mapping. A value can be used to find its member name:
console.log(Level[1]); // "Medium"This can be useful for debugging, but it also means numeric values from untrusted input can be easy to accept accidentally. Validate external numbers before treating them as enum members.
String enums
String enums assign readable runtime values. Each member must have an initializer.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
function paint(color: Color): void {
console.log(`Painting ${color}`);
}
paint(Color.Red); // Painting REDString enums do not have reverse mappings. Color["RED"] does not return Color.Red. Also, a string literal is not accepted where the enum type is expected:
paint("RED"); // ErrorCallers must use Color.Red, which gives the enum a distinct API.
What enums compile to
Enums are runtime objects, unlike type-only unions. A numeric enum compiles to JavaScript similar to this:
var Level;
(function (Level) {
Level[Level["Low"] = 0] = "Low";
Level[Level["Medium"] = 1] = "Medium";
Level[Level["High"] = 2] = "High";
})(Level || (Level = {}));The assignments create both Level.Medium, which is 1, and Level[1], which is "Medium". A string enum compiles to an object containing only forward mappings, such as Color.Red = "RED".
Exercise
What does Level[0] return for the numeric enum in this chapter?
Show answer
It returns the string "Low".