Challenge - 5 Problems
Typeof Type Guards Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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));
Attempts:
2 left
💡 Hint
Think about how typeof narrows the type inside the if block.
✗ Incorrect
The typeof check narrows the union type. Since 42 is a number, the else block runs, calling toFixed(1) which formats the number with one decimal place.
❓ Predict Output
intermediate2: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));
Attempts:
2 left
💡 Hint
typeof narrows unknown to boolean inside the if.
✗ Incorrect
The typeof check confirms the value is boolean, so the ternary returns 'Yes' for true.
❓ Predict Output
advanced2: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' }));
Attempts:
2 left
💡 Hint
typeof returns 'object' for objects, so else block runs.
✗ Incorrect
Since input is an object, the else block runs and accesses input.name safely.
❓ Predict Output
advanced2: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));
Attempts:
2 left
💡 Hint
Check the order of typeof checks and the final else block.
✗ Incorrect
The value is boolean false, so the final else block runs and returns 'False'.
🧠 Conceptual
expert2:00remaining
Why typeof type guards cannot distinguish arrays
Why does
typeof fail to distinguish arrays from objects in TypeScript?Attempts:
2 left
💡 Hint
Think about what typeof returns for arrays in JavaScript.
✗ Incorrect
In JavaScript and TypeScript, typeof returns 'object' for arrays, so typeof cannot distinguish arrays from plain objects.