Bird
Raised Fist0
Typescriptprogramming~15 mins

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

Choose your learning style10 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
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
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
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
Hint

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

Practice

(1/5)
1. What does a literal type in TypeScript allow you to do?
easy
A. Specify exact allowed values for a variable
B. Create a new class
C. Define a function return type as any
D. Ignore type checking

Solution

  1. Step 1: Understand the purpose of literal types

    Literal types let you restrict a variable to exact values like 'yes' or 10 instead of general types like string or number.
  2. Step 2: Compare options with the definition

    Only Specify exact allowed values for a variable correctly describes this feature; others describe unrelated concepts.
  3. Final Answer:

    Specify exact allowed values for a variable -> Option A
  4. Quick Check:

    Literal types = exact allowed values [OK]
Hint: Literal types fix variable values exactly [OK]
Common Mistakes:
  • Confusing literal types with classes
  • Thinking literal types disable type checking
  • Assuming literal types allow any value
2. Which of the following is the correct way to declare a variable with a literal type of the string 'open' in TypeScript?
easy
A. let status = 'open';
B. let status: string = 'open';
C. let status: 'open' = 'open';
D. let status: 'open'; status = 'closed';

Solution

  1. Step 1: Check the syntax for literal type declaration

    To declare a variable with a literal type, you specify the exact value in quotes as the type, like 'open'.
  2. Step 2: Evaluate each option

    let status: 'open' = 'open'; correctly declares status with type 'open' and assigns 'open'. let status: string = 'open'; uses string type, not literal. let status = 'open'; infers string type but not literal. let status: 'open'; status = 'closed'; declares type 'open' but assigns 'closed', which is invalid.
  3. Final Answer:

    let status: 'open' = 'open'; -> Option C
  4. Quick Check:

    Literal type syntax uses exact value in quotes [OK]
Hint: Use quotes around value to declare literal type [OK]
Common Mistakes:
  • Assigning a different value than the literal type
  • Using general types instead of literal types
  • Omitting the type and expecting literal type
3. What will be the output of the following TypeScript code?
type Direction = 'left' | 'right';
function move(dir: Direction) {
  if (dir === 'left') {
    return 'Moving left';
  } else {
    return 'Moving right';
  }
}
console.log(move('right'));
medium
A. Moving right
B. Type error at compile time
C. Moving left
D. Undefined

Solution

  1. Step 1: Understand the function behavior with literal type

    The function move accepts only 'left' or 'right'. It returns 'Moving left' if input is 'left', else 'Moving right'.
  2. Step 2: Trace the function call with 'right'

    Calling move('right') triggers the else branch, returning 'Moving right'.
  3. Final Answer:

    Moving right -> Option A
  4. Quick Check:

    Input 'right' returns 'Moving right' [OK]
Hint: Check input matches condition for output [OK]
Common Mistakes:
  • Confusing which branch runs for 'right'
  • Expecting compile error for valid literal
  • Ignoring else branch
4. Identify the error in this TypeScript code using literal types and value narrowing:
type Status = 'success' | 'error';
function handle(status: Status) {
  if (status === 'success') {
    console.log('Success!');
  } else if (status === 'fail') {
    console.log('Failed!');
  }
}
medium
A. Missing return type in function
B. No error, code is correct
C. Variable status is not declared
D. The else if condition checks an invalid literal 'fail'

Solution

  1. Step 1: Check the allowed literal types for Status

    Status can only be 'success' or 'error'.
  2. Step 2: Analyze the else if condition

    The code checks if status === 'fail', which is not part of Status type, causing a type error.
  3. Final Answer:

    The else if condition checks an invalid literal 'fail' -> Option D
  4. Quick Check:

    Check conditions must match literal types [OK]
Hint: Check all compared literals are in the type union [OK]
Common Mistakes:
  • Using literals not declared in the union type
  • Ignoring TypeScript errors on invalid comparisons
  • Assuming missing return type causes error here
5. Given the following TypeScript code, what is the type of variable result after the if statement?
type Mode = 'auto' | 'manual';
function setMode(mode: Mode) {
  let result: string | undefined;
  if (mode === 'auto') {
    result = 'Automatic mode set';
  } else {
    result = undefined;
  }
  return result;
}
hard
A. string
B. string | undefined
C. undefined
D. Mode

Solution

  1. Step 1: Analyze variable declaration and assignments

    Variable result is declared as string | undefined. Inside if, assigned string; else assigned undefined.
  2. Step 2: Determine narrowed type after if

    Since result can be either string or undefined depending on mode, its type remains string | undefined.
  3. Final Answer:

    string | undefined -> Option B
  4. Quick Check:

    Variable type includes all assigned values [OK]
Hint: Variable type covers all assigned values after narrowing [OK]
Common Mistakes:
  • Assuming type narrows to string only
  • Ignoring undefined assignment
  • Confusing Mode type with result type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard