Bird
Raised Fist0
Typescriptprogramming~10 mins

Literal types and value narrowing in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Literal types and value narrowing
Declare variable with literal type
↓
Assign specific literal value
↓
Use variable in condition
↓
Execute narrowed
↓
End
Start with a variable having a literal type, then check its value in a condition to narrow its type and run specific code.
Execution Sample
Typescript
let status: "success" | "error" = "success";
if (status === "success") {
  console.log("Operation succeeded");
} else {
  console.log("Operation failed");
}
This code sets a variable to a literal type and uses a condition to narrow its value and print a message.
Execution Table
StepVariable 'status'Condition 'status === "success"'Branch TakenOutput
1"success"trueYes branch"Operation succeeded"
2"error"falseNo branch"Operation failed"
💡 Condition is true at step 1, so 'Yes branch' executes and program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
status"success""success""success""success"
Key Moments - 2 Insights
Why does the 'if' condition narrow the type of 'status'?
Because the condition checks if 'status' equals the literal "success", TypeScript knows inside the 'if' block 'status' must be exactly "success" (see execution_table step 1).
What happens if 'status' is not "success"?
The 'else' branch runs, meaning 'status' is narrowed to "error" there (see execution_table step 2 where condition is false).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'status' at step 1?
A"error"
B"success"
Cundefined
Dnull
💡 Hint
Check the 'Variable status' column in execution_table row for step 1.
At which step does the condition 'status === "success"' evaluate to false?
AStep 2
BStep 1
CNever
DBoth steps
💡 Hint
Look at the 'Condition' column in execution_table for each step.
If we change 'status' initial value to "error", what will happen at step 1?
ACondition is true, 'Yes branch' runs
BError: type mismatch
CCondition is false, 'No branch' runs
DProgram crashes
💡 Hint
Refer to variable_tracker and execution_table logic for condition evaluation.
Concept Snapshot
Literal types hold exact values like "success" or "error".
Type narrowing happens when conditions check these values.
Inside 'if (status === "success")', 'status' is known to be "success".
Else branch means 'status' is the other literal.
This helps TypeScript catch errors and guide code flow.
Full Transcript
This example shows a variable 'status' declared with literal types "success" or "error". It is assigned "success". The 'if' condition checks if 'status' equals "success". When true, the code inside the 'if' runs, printing "Operation succeeded". This narrows the type of 'status' to the literal "success" inside that block. If the condition were false, the 'else' block would run, meaning 'status' is "error" there. The execution table traces these steps, showing the variable value, condition result, branch taken, and output. The variable tracker confirms 'status' stays "success" throughout. Key moments clarify how TypeScript uses these checks to narrow types and why branches run. The quiz tests understanding of variable values and condition results at each step. This helps beginners see how literal types and narrowing work in practice.

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