Bird
Raised Fist0
Typescriptprogramming~10 mins

typeof type guards in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - typeof type guards
Start with variable
↓
Check typeof variable
↓
Handle string
↓
End
Check the type of a variable using typeof, then run code based on the type.
Execution Sample
Typescript
function printValue(x: string | number) {
  if (typeof x === 'string') {
    console.log('String:', x.toUpperCase());
  } else {
    console.log('Number:', x.toFixed(2));
  }
}
This code checks if x is a string or number and prints it differently.
Execution Table
StepVariable xConditionCondition ResultBranch TakenOutput
1'hello'typeof x === 'string'trueif branchString: HELLO
242typeof x === 'string'falseelse branchNumber: 42.00
3truetypeof x === 'string'falseelse branchNumber: Error (not handled)
💡 Execution stops after handling each input once.
Variable Tracker
Variable xStartAfter Step 1After Step 2After Step 3
xundefined'hello'42true
Key Moments - 2 Insights
Why does the code use typeof x === 'string' instead of x instanceof String?
typeof checks the primitive type directly, which works for string literals. instanceof checks object wrappers, which is less common and can cause confusion. See execution_table step 1 for typeof usage.
What happens if x is a boolean like true?
The else branch runs because typeof x === 'string' is false, but the code assumes number in else, causing an error. See execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when x is 'hello'?
AString: hello
BNumber: 42.00
CString: HELLO
DError
💡 Hint
Check row 1 in execution_table under Output column.
At which step does the condition typeof x === 'string' evaluate to false?
AStep 1
BStep 3
CStep 2
DNone
💡 Hint
Look at Condition Result column in execution_table for steps 2 and 3.
If we add a check for typeof x === 'boolean', what would change in the execution table?
AStep 1 would change output
BStep 3 would take a new branch for boolean
CStep 2 would become true
DNo change
💡 Hint
Refer to key_moments about boolean input and execution_table step 3.
Concept Snapshot
typeof type guards check a variable's type at runtime.
Syntax: if (typeof x === 'string') { ... } else { ... }
Allows safe use of type-specific methods.
Common types: 'string', 'number', 'boolean', 'undefined', 'object', 'function'.
Use to avoid errors when handling union types.
Full Transcript
This example shows how to use typeof type guards in TypeScript. The function printValue takes a variable x that can be a string or number. It checks if x is a string using typeof x === 'string'. If true, it prints the uppercase string. Otherwise, it treats x as a number and prints it with two decimals. The execution table shows three steps with different x values: 'hello', 42, and true. For 'hello', the condition is true and prints the uppercase string. For 42, the condition is false and prints the number. For true, the condition is false but the code assumes number, which can cause an error. The variable tracker shows how x changes each step. Key moments explain why typeof is used and what happens with unexpected types. The quiz tests understanding of outputs and condition results. The snapshot summarizes how typeof type guards work to safely handle different types in code.

Practice

(1/5)
1. What does the typeof operator do in TypeScript when used as a type guard?
easy
A. It declares a new variable with a specific type.
B. It converts a variable to a string type.
C. It checks the runtime type of a variable to narrow its type inside a condition.
D. It creates a new type alias for a variable.

Solution

  1. Step 1: Understand the purpose of typeof

    The typeof operator checks the actual type of a value at runtime, like 'string' or 'number'.
  2. Step 2: Recognize its use as a type guard

    Using typeof in an if condition helps TypeScript know the exact type inside that block, making code safer.
  3. Final Answer:

    It checks the runtime type of a variable to narrow its type inside a condition. -> Option C
  4. Quick Check:

    typeof narrows type [OK]
Hint: typeof checks actual type at runtime to narrow types [OK]
Common Mistakes:
  • Thinking typeof changes the variable's type
  • Confusing typeof with type declarations
  • Assuming typeof works at compile time only
2. Which of the following is the correct syntax to use typeof as a type guard in TypeScript?
easy
A. if (typeof x === 'string') { /* code */ }
B. if (typeof x = 'string') { /* code */ }
C. if (typeof x == string) { /* code */ }
D. if (typeof x === string) { /* code */ }

Solution

  1. Step 1: Check the correct comparison operator

    The strict equality operator === is required to compare typeof result with a string.
  2. Step 2: Verify the string literal format

    The type name must be a string literal like 'string', 'number', etc., inside quotes.
  3. Final Answer:

    if (typeof x === 'string') { /* code */ } -> Option A
  4. Quick Check:

    Correct typeof syntax uses === and quotes [OK]
Hint: Use === and quotes around type name in typeof checks [OK]
Common Mistakes:
  • Using single = instead of ===
  • Not putting type name in quotes
  • Using == instead of ===
3. What will be the output of this TypeScript code?
function checkValue(x: string | number) {
  if (typeof x === 'string') {
    return x.toUpperCase();
  } else {
    return x.toFixed(2);
  }
}
console.log(checkValue(3.14159));
medium
A. '3.14'
B. '3.14' as a string
C. '3.14' as a number
D. '3.14' as a string with two decimals

Solution

  1. Step 1: Identify the type of input

    The input is 3.14159, which is a number, so the else block runs.
  2. Step 2: Understand the else block behavior

    The else block calls toFixed(2) on the number, which returns a string with 2 decimals: '3.14'.
  3. Final Answer:

    '3.14' as a string with two decimals -> Option D
  4. Quick Check:

    Number input uses toFixed(2) = '3.14' [OK]
Hint: toFixed(2) returns string with 2 decimals [OK]
Common Mistakes:
  • Thinking toFixed returns a number
  • Confusing string and number outputs
  • Ignoring the else block
4. Find the error in this TypeScript code using typeof type guard:
function process(value: string | boolean) {
  if (typeof value === 'boolean') {
    return value.toUpperCase();
  } else {
    return value;
  }
}
medium
A. The typeof check should be for 'string' instead of 'boolean'.
B. Calling toUpperCase() on a boolean value causes an error.
C. The else block should convert value to boolean.
D. There is no error; the code is correct.

Solution

  1. Step 1: Analyze the typeof condition

    The condition checks if value is a boolean.
  2. Step 2: Check method call on boolean

    Inside the if block, it calls toUpperCase(), which exists only on strings, not booleans, causing an error.
  3. Final Answer:

    Calling toUpperCase() on a boolean value causes an error. -> Option B
  4. Quick Check:

    toUpperCase() invalid on boolean [OK]
Hint: Check method exists on type before calling [OK]
Common Mistakes:
  • Assuming booleans have string methods
  • Mixing up type guard conditions
  • Ignoring method compatibility
5. Given this function, what is the correct way to safely handle a variable that can be string, number, or boolean using typeof type guards?
function formatValue(val: string | number | boolean) {
  // Fill in the blanks
}
hard
A. Use separate if blocks: if typeof val === 'string', else if 'number', else if 'boolean', then handle each accordingly.
B. Use a single if block checking if typeof val === 'string' and treat others as strings.
C. Convert val to string directly without typeof checks.
D. Use typeof val === 'object' to handle all types.

Solution

  1. Step 1: Recognize multiple possible types

    The variable can be string, number, or boolean, so each needs separate handling.
  2. Step 2: Use multiple typeof checks

    Use if-else if blocks checking typeof val === 'string', 'number', and 'boolean' to safely handle each type.
  3. Final Answer:

    Use separate if blocks: if typeof val === 'string', else if 'number', else if 'boolean', then handle each accordingly. -> Option A
  4. Quick Check:

    Multiple typeof checks for multiple types [OK]
Hint: Check each type separately with typeof for safety [OK]
Common Mistakes:
  • Handling all types as strings blindly
  • Using typeof 'object' for primitives
  • Skipping boolean type handling
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