Using Numeric Enums
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 52 of 73.
You can use an enum as a type annotation just like any other TypeScript type. When you specify an enum as a parameter type, TypeScript ensures that only valid enum values can be passed to that function:
function processUser(role: UserRole): void {
if (role === UserRole.Admin) {
console.log("Full access granted");
} else if (role === UserRole.Editor) {
console.log("Edit access granted");
} else {
console.log("View access only");
}
}This approach provides excellent type safety - TypeScript will catch any attempts to pass invalid values, and your code editor will offer autocompletion for the available enum members. You can call this function using processUser(UserRole.Admin) or even processUser(0), since numeric enums accept their underlying numeric values.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function named checkPermissions that takes one parameter:
roleof typeUserRole(using the enum from the previous lesson)
The function should:
- Check the role value and print different messages based on the role
- If the role is
UserRole.Admin, print"Full access granted" - If the role is
UserRole.Editor, print"Edit access granted" - For any other role, print
"View access only" - Have a return type of
void
You are provided with the following from the previous challenge:
- The
UserRoleenum withAdmin,Editor, andViewermembers - Variables:
adminRole,editorRole, andviewerRole
Create a variable named currentUser of type UserRole and assign it UserRole.Editor.
Create a variable named guestUser of type UserRole and assign it the numeric value 2.
Print the following outputs by calling your checkPermissions function:
- Call
checkPermissionswithadminRole - Call
checkPermissionswithcurrentUser - Call
checkPermissionswithguestUser - Call
checkPermissionswithUserRole.Admin - Call
checkPermissionswith the numeric value0
Cheat sheet
Use enums as type annotations for function parameters to ensure type safety:
function processUser(role: UserRole): void {
if (role === UserRole.Admin) {
console.log("Full access granted");
} else if (role === UserRole.Editor) {
console.log("Edit access granted");
} else {
console.log("View access only");
}
}You can call enum-typed functions with enum members or their underlying numeric values:
processUser(UserRole.Admin); // Using enum member
processUser(0); // Using numeric valueTypeScript provides autocompletion and catches invalid values when using enum type annotations.
Try it yourself
// Provided from previous challenge
enum UserRole {
Admin,
Editor,
Viewer
}
const adminRole = UserRole.Admin;
const editorRole = UserRole.Editor;
const viewerRole = UserRole.Viewer;
// TODO: Write your code here
// Create the checkPermissions function
// Create currentUser variable
// Create guestUser variable
// Call checkPermissions with the required parametersThis 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