Menu
Coddy logo textTech

What is a Numeric Enum?

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 51 of 73.

TypeScript enums provide a way to give meaningful names to a set of related numeric values. Instead of using magic numbers throughout your code, enums let you create a collection of named constants that make your code more readable and maintainable.

A numeric enum is declared using the enum keyword. By default, TypeScript automatically assigns numeric values starting from 0 and incrementing by 1 for each member:

enum Status {
  Pending,    // 0
  Processing, // 1
  Complete    // 2
}

This creates three constants: Status.Pending equals 0, Status.Processing equals 1, and Status.Complete equals 2. You can also explicitly set the starting value, and subsequent members will continue incrementing from that point.

challenge icon

Challenge

Easy

Create a numeric enum named UserRole with three members: Admin, Editor, and Viewer.

Create three variables to demonstrate the enum values:

  • adminRole of type UserRole and assign it UserRole.Admin
  • editorRole of type UserRole and assign it UserRole.Editor
  • viewerRole of type UserRole and assign it UserRole.Viewer

Print the following outputs on separate lines:

  • Print the value of adminRole
  • Print the value of editorRole
  • Print the value of viewerRole
  • Print the numeric value of UserRole.Admin
  • Print the numeric value of UserRole.Editor
  • Print the numeric value of UserRole.Viewer

Try it yourself

// TODO: Write your code here
// Create the UserRole enum and variables as described in the challenge

// Print the required outputs
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript