Sub topic 5
Numeric enums
This chapter assumes you know basic TypeScript types, can annotate functions, and are comfortable with switch statements and object literals. Earlier chapters covered literal types and unions of literals. Here you will look at the first kind of enum TypeScript offers, the numeric enum. It is the default form, and it behaves differently from the literal unions you have seen so far.
What a numeric enum is
An enum is a named set of constants. In a numeric enum, each member is a number. You declare one with the enum keyword:
enum Level {
Low,
Medium,
High,
}
console.log(Level.Low); // 0
console.log(Level.Medium); // 1
console.log(Level.High); // 2If you give no initializer, the first member is 0. Each later member is the previous member's value plus one.
An enum declares both a type and a value:
- As a type,
Leveldescribes the allowed values. You can writefunction f(level: Level). - As a value,
Levelis an object that exists at runtime. You can writeLevel.Highin an expression.
Union types have no runtime object like this. They exist only for the compiler. That difference is the main reason to choose between the two, and a later chapter covers the decision in full.
How member values are assigned
The compiler follows a fixed rule for each member's value. The diagram shows it.
Explicit initializers
You can set any member's value. Members after it count up from that value:
enum HttpStatus {
Ok = 200,
Created, // 201
Accepted, // 202
BadRequest = 400,
NotFound = 404,
}
console.log(HttpStatus.Created); // 201
console.log(HttpStatus.Accepted); // 202Explicit values suit enums that mirror an external contract such as HTTP codes, database columns, or a wire protocol. Auto-numbering is risky there. If someone inserts a member in the middle, every later value shifts, and any data you saved with the old numbers now means something different. When the numbers matter outside your program, write them out.
Constant and computed members
Initializers fall into two groups:
- A constant member's value is known at compile time. Examples are number literals, references to earlier members, and arithmetic or bitwise operators on those.
- A computed member's value is only known when the code runs, for example a function call or a property access.
enum Mixed {
A = "abc".length, // computed
B = 10, // constant
C, // 11, because B is constant
}A member right after a computed member needs its own initializer. Without one, the compiler can't know what "previous plus one" means. This is the error branch in the diagram, and it reads Enum member must have initializer. Here A is computed and B has an explicit value, so the enum compiles.
Bit flags
Constant expressions let you build bit flag sets. Each flag is a power of two, so you can combine flags in one number:
enum Permission {
None = 0,
Read = 1 << 0, // 1
Write = 1 << 1, // 2
Execute = 1 << 2, // 4
All = Read | Write | Execute, // 7
}
function can(mask: Permission, needed: Permission): boolean {
return (mask & needed) === needed;
}
const mine: Permission = Permission.Read | Permission.Write;
console.log(can(mine, Permission.Write)); // true
console.log(can(mine, Permission.Execute)); // false
console.log(mine); // 3Notice the last line. The combined value 3 is not a named member of Permission, yet it is a legal Permission value in this pattern. Bit flags are the case where this looseness helps. The next section covers where it hurts.
How strict is the type?
A numeric enum type is looser than most people expect. There are three rules to know.
- An enum member is assignable to
number. - Any value of type
numberis assignable to a numeric enum type. - Since TypeScript 5.0, a number literal that matches no member is rejected.
enum Level {
Low,
Medium,
High,
}
function setLevel(level: Level): void {
console.log(`Level set to ${level}`);
}
const fromEnum: number = Level.High; // OK (rule 1)
const raw: number = 7;
setLevel(raw); // OK, no error (rule 2)
setLevel(7); // Error in TypeScript 5.0+: Argument of type '7' is not assignable to parameter of type 'Level'. (rule 3)Rule 2 is the usual weak spot. The compiler can't tell that raw holds 7, so it accepts the call. Data from JSON, a form field, or a database is typed number, and it flows into your enum-typed code unchecked. If that data can be wrong, validate it yourself before you treat it as a Level:
function isLevel(value: number): value is Level {
return value in Level && typeof Level[value as Level] === "string";
}The check works because of reverse mapping, covered below. Level[7] is undefined, so 7 fails the test. Be careful with enums that have explicit gaps or duplicate values. A check built on reverse mapping reflects exactly what the enum object contains.
Reverse mapping
A numeric enum's runtime object maps in both directions. You can look up a number from a name, and a name from a number:
enum Level {
Low,
Medium,
High,
}
console.log(Level.Medium); // 1
console.log(Level[1]); // "Medium"
console.log(Level["High"]); // 2This is useful for logging and for showing a readable name where you stored a number. Two details matter:
- Only numeric members get a reverse entry. String members, covered in the next chapter, do not.
- If two members share a value, the later declaration wins the reverse lookup.
enum Duplicate {
First = 1,
Second = 1,
}
console.log(Duplicate[1]); // "Second"
console.log(Duplicate.First); // 1
console.log(Duplicate.First === Duplicate.Second); // trueBoth names still resolve forward to 1. Only the number-to-name lookup loses information.
The iteration trap
The reverse mapping puts both directions into one object, so enumerating it returns twice as many entries as you have members:
enum Level {
Low,
Medium,
High,
}
console.log(Object.keys(Level));
// ["0", "1", "2", "Low", "Medium", "High"]
console.log(Object.values(Level));
// ["Low", "Medium", "High", 0, 1, 2]JavaScript lists integer-like keys first in ascending order, then the other keys in insertion order. To get only the member names or only the values, filter by type:
const names = Object.keys(Level).filter((key) => Number.isNaN(Number(key)));
const values = Object.values(Level).filter(
(value): value is Level => typeof value === "number",
);
console.log(names); // ["Low", "Medium", "High"]
console.log(values); // [0, 1, 2]This filter is the price of reverse mapping. If your code often needs to iterate over the members, that is a reason to consider a constant object instead of an enum, a trade-off a later chapter discusses.
Enum members as types
When every member of an enum is a constant with a literal value, the enum becomes a union enum. Each member is a type of its own, and the enum type is the union of its members:
enum Level {
Low,
Medium,
High,
}
function label(level: Level): string {
switch (level) {
case Level.Low:
return "low";
case Level.Medium:
return "medium";
case Level.High:
return "high";
}
}
const only: Level.High = Level.High; // a single member used as a typeInside the switch, TypeScript narrows level in each case. After all three cases, nothing is left, so the function needs no return at the end. The exhaustiveness pattern with never appears in a later chapter and works on union enums the same way.
A computed member breaks this. An enum that includes a computed member is not a union enum, so its members are not individual types and narrowing by member no longer works. Keep numeric enums that you want to switch over free of computed members.
What the compiler emits
An enum produces real JavaScript. Level compiles to roughly this:
var Level;
(function (Level) {
Level[Level["Low"] = 0] = "Low";
Level[Level["Medium"] = 1] = "Medium";
Level[Level["High"] = 2] = "High";
})(Level || (Level = {}));Each line does two assignments in one expression. Level["Low"] = 0 returns 0, and is then used as the key in Level[0] = "Low". This is the reverse mapping, and it explains the doubled output from Object.keys. The next chapters cover this output in more detail.
Because the enum is a runtime object, it adds code to your bundle. It also has consequences for tools that strip types without running the full compiler. Those tools can only erase type annotations. They cannot generate an enum's object from a type-level description, so they need explicit support for enums.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Relying on auto-numbering for saved or transmitted values | Inserting a member shifts later values and corrupts stored data | Write explicit values for anything persisted or sent |
| Treating a `number` from input as a `Level` | The compiler accepts it, and invalid values pass through | Validate with a check like `isLevel` before use |
| Looping with `Object.keys(Level)` | Names and numbers are mixed together | Filter by `typeof` or use `Number.isNaN` |
| Placing a member after a computed one without an initializer | Compile error | Give the member an explicit value |
| Giving two members the same value, then using reverse lookup | The later name wins, silently | Avoid duplicates unless you want aliases |
Exercises
Exercise
Given enum Step { Start = 10, Middle, End = 20, Finish }, what are the values of Step.Middle and Step.Finish, and what does Step[11] evaluate to?
Show answer
Step.Middle is 11 because it follows Start = 10, and Step.Finish is 21 because it follows End = 20. Step[11] is "Middle" through the reverse mapping.
Exercise
A function takes level: Level, where Level is a numeric enum with members 0, 1 and 2. You call it with a variable declared as const n: number = 99. Does the compiler report an error, and what should you do if n comes from a JSON request body?
Show answer
The compiler reports no error, because any number is assignable to a numeric enum type. Because the value comes from outside your program, validate it at runtime before the call, for example by checking that Level[n] is a string, and reject the request if the check fails.
Exercise
Write the expression that returns only the numeric values of enum Direction { North, East, South, West } as Direction[], and say why the filter is needed.
Show answer
Object.values(Direction).filter((v): v is Direction => typeof v === "number"). The filter is needed because the reverse mapping puts both the names and the numbers on the enum object, so Object.values returns strings and numbers together.