Sub topic 5
Numeric enums
This chapter assumes you know basic TypeScript types, function annotations, object literals, and JavaScript switch statements. A numeric enum is useful when a program needs a named set of numeric values, such as priority levels, states, or protocol codes.
Declaring a numeric enum
An enum is a TypeScript feature that defines named constants. A numeric enum assigns numbers to its members.
enum Level {
Low,
Medium,
High,
}
const current: Level = Level.Medium;
console.log(current); // 1When no value is written, the first member receives 0. Each following member increases by 1:
| Member | Numeric value |
|---|---|
| `Level.Low` | `0` |
| `Level.Medium` | `1` |
| `Level.High` | `2` |
The enum member names make code easier to read than unexplained numbers. Level.High communicates intent more clearly than 2.
You can also assign the first value explicitly. The following members continue counting from it:
enum HttpStatus {
Ok = 200,
NotFound,
ServerError,
}
console.log(HttpStatus.Ok); // 200
console.log(HttpStatus.NotFound); // 201
console.log(HttpStatus.ServerError); // 202If these numbers represent fixed external codes, assign every value explicitly. Automatic numbering is convenient, but inserting a member in the middle can change the values of later members.
enum Before {
Low, // 0
Medium, // 1
High, // 2
}
enum After {
Low, // 0
Urgent, // 1
Medium, // 2
High, // 3
}That change can break persisted data, network messages, or database rows that store the numeric values.
Using numeric enum members
An enum creates a type that you can use in function parameters, variables, and object properties.
enum Direction {
Up,
Down,
Left,
Right,
}
function move(direction: Direction): string {
switch (direction) {
case Direction.Up:
return "Moving up";
case Direction.Down:
return "Moving down";
case Direction.Left:
return "Moving left";
case Direction.Right:
return "Moving right";
}
}
console.log(move(Direction.Left));TypeScript checks that callers provide a value compatible with Direction. Passing an arbitrary string is rejected:
move("left"); // ErrorNumeric enums have an important compatibility rule: numbers can sometimes be assigned to them. For example:
enum Permission {
Read = 1,
Write = 2,
}
const permission: Permission = 1; // AllowedThis is convenient when reading numeric codes from an existing API, but it also means that an invalid number may pass the type checker:
const unknownPermission: Permission = 999; // Allowed by TypeScriptValidate untrusted numbers at runtime before treating them as enum members.
Runtime objects and reverse mapping
Enums exist at runtime. The compiler emits an object containing the names and values. Numeric enums also support reverse lookup: a number can be used to find its member name.
enum Level {
Low,
Medium,
High,
}
console.log(Level.Medium); // 1
console.log(Level[1]); // "Medium"The generated JavaScript behaves conceptually like this:
var Level;
(function (Level) {
Level[Level["Low"] = 0] = "Low";
Level[Level["Medium"] = 1] = "Medium";
Level[Level["High"] = 2] = "High";
})(Level || (Level = {}));The assignment sets both directions:
Level.Mediumreturns1.Level[1]returns"Medium".
This reverse mapping can help with logging, but it adds runtime code and can surprise code that enumerates the object’s keys.
Choosing automatic or explicit values
Use automatic values for internal states when the exact numbers do not leave the program. Use explicit values when numbers are part of a file format, database schema, API contract, or hardware protocol.
Exercise
What value does State.Ready receive, and why might this be unsafe for a stored format? enum State { New, Ready, Done }
Show answer
State.Ready receives 1. Adding a member before Ready would change that value, which could make previously stored data mean something different.