0
0
Typescriptprogramming~15 mins

Literal types and value narrowing in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Literal types and value narrowing
📖 Scenario: You are building a simple TypeScript program to handle user roles in a system. Each user can have a specific role, and you want to make sure the program only accepts certain exact role names. This helps avoid mistakes like typos.
🎯 Goal: Create a TypeScript program that uses literal types to define exact user roles and uses value narrowing to check and print messages based on the user's role.
📋 What You'll Learn
Use a literal type to define user roles as 'admin', 'editor', or 'viewer'.
Create a variable with one of these roles.
Use a function that takes the role and uses value narrowing with a switch statement.
Print a specific message for each role.
💡 Why This Matters
🌍 Real World
Defining exact user roles helps prevent bugs and makes your program safer by only allowing known values.
💼 Career
Many jobs require writing code that handles specific fixed values safely, especially in user management and permissions.
Progress0 / 4 steps
1
Define user roles with literal types
Create a type called UserRole that can only be one of these exact strings: 'admin', 'editor', or 'viewer'. Then create a variable called currentUserRole and set it to 'editor'.
Typescript
Need a hint?

Use the pipe symbol | to combine string literals into a type.

2
Create a function to check user role
Write a function called getRoleMessage that takes a parameter role of type UserRole. Inside the function, use a switch statement on role to prepare a message string for each role: 'admin' should return 'You have full access.', 'editor' should return 'You can edit content.', and 'viewer' should return 'You can view content.'. Return the message string.
Typescript
Need a hint?

Use a switch statement to check the exact value of role and return the correct message.

3
Call the function with the current user role
Create a variable called message and set it to the result of calling getRoleMessage with currentUserRole as the argument.
Typescript
Need a hint?

Call the function with the variable currentUserRole and save the result in message.

4
Print the role message
Write a console.log statement to print the value of the message variable.
Typescript
Need a hint?

Use console.log(message) to show the message in the console.