Bird
Raised Fist0
Typescriptprogramming~20 mins

typeof type guards in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Typeof Type Guards Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of typeof type guard with union types
What is the output of this TypeScript code when calling checkType(42)?
Typescript
function checkType(value: string | number) {
  if (typeof value === 'string') {
    return `String: ${value.toUpperCase()}`;
  } else {
    return `Number: ${value.toFixed(1)}`;
  }
}

console.log(checkType(42));
A"Number: 42.0"
B"String: 42"
CCompilation error
DTypeError at runtime
Attempts:
2 left
💡 Hint
Think about how typeof narrows the type inside the if block.
❓ Predict Output
intermediate
2:00remaining
Using typeof type guard with unknown type
What will this code output when processValue(true) is called?
Typescript
function processValue(value: unknown) {
  if (typeof value === 'boolean') {
    return value ? 'Yes' : 'No';
  }
  return 'Not a boolean';
}

console.log(processValue(true));
A"true"
B"Yes"
C"Not a boolean"
DRuntime error
Attempts:
2 left
💡 Hint
typeof narrows unknown to boolean inside the if.
❓ Predict Output
advanced
2:00remaining
Effect of typeof type guard on union with object
What is the output of this code snippet?
Typescript
function describe(input: string | { name: string }) {
  if (typeof input === 'string') {
    return `String: ${input}`;
  } else {
    return `Object with name: ${input.name}`;
  }
}

console.log(describe({ name: 'Alice' }));
ACompilation error
B"String: [object Object]"
C"Object with name: Alice"
DTypeError: Cannot read property 'name' of undefined
Attempts:
2 left
💡 Hint
typeof returns 'object' for objects, so else block runs.
❓ Predict Output
advanced
2:00remaining
typeof type guard with nested conditions
What will this code print when formatValue(false) is called?
Typescript
function formatValue(val: string | number | boolean) {
  if (typeof val === 'string') {
    return val.toUpperCase();
  } else if (typeof val === 'number') {
    return val.toFixed(2);
  } else {
    return val ? 'True' : 'False';
  }
}

console.log(formatValue(false));
ARuntime error
B"false"
C"0.00"
D"False"
Attempts:
2 left
💡 Hint
Check the order of typeof checks and the final else block.
🧠 Conceptual
expert
2:00remaining
Why typeof type guards cannot distinguish arrays
Why does typeof fail to distinguish arrays from objects in TypeScript?
ABecause typeof returns 'object' for both arrays and objects, so it cannot differentiate them.
BBecause arrays are primitive types and typeof returns 'array' for them.
CBecause TypeScript disables typeof checks on arrays for performance reasons.
DBecause arrays have a special typeof value 'array' that is not recognized by TypeScript.
Attempts:
2 left
💡 Hint
Think about what typeof returns for arrays in JavaScript.

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