0
0
Typescriptprogramming~20 mins

typeof type guards in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 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.