TypeScriptBasic types
enum
A named set of constant values, either numbers or strings.
Example
#TypeScript
enum Difficulty {
Easy = 'easy',
Medium = 'medium',
Hard = 'hard'
}
function label(level: Difficulty): string {
return level === Difficulty.Hard ? 'For the brave' : 'For everyone'
}
console.log(Difficulty.Hard)
console.log(label(Difficulty.Easy))Result
hard For everyone
Definition and usage
#An enum (an enumerated type) groups related constants under one shared name, for example difficulty levels or order statuses. Instead of writing “magic” strings in your code, you reference Difficulty.Hard.
Numeric enums get consecutive numbers starting from zero, unless you provide your own. String enums require a value for every member, and they’re easier to read in logs and in data from an API.
Unlike most TypeScript syntax, an enum also exists after compilation, as a JavaScript object. That’s why many teams use a literal union ("easy" | "hard") or an object with as const instead of an enum.
Syntax
#Syntax
enum Name {
First = "value",
Second = "value"
}More examples
#TypeScript
enum Status {
Draft,
Published,
Archived
}
console.log(Status.Published)
console.log(Status[2])Result
1 Archived
Good practices
#- For data from an API and from localStorage, choose string enums. The value
"hard"is easier to understand than2. - Consider a literal union,
type Difficulty = "easy" | "hard". It’s lighter and generates no code.
Related entries
#Spotted a mistake or missing an example? Write to us.