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
EasyCreate a numeric enum named UserRole with three members: Admin, Editor, and Viewer.
Create three variables to demonstrate the enum values:
adminRoleof typeUserRoleand assign itUserRole.AdmineditorRoleof typeUserRoleand assign itUserRole.EditorviewerRoleof typeUserRoleand assign itUserRole.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 outputsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples