Challenge - 5 Problems
Type Narrowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of type narrowing with typeof in conditional
What is the output of this TypeScript code when run with
input = 42?Typescript
function checkType(input: string | number) { if (typeof input === 'string') { return input.toUpperCase(); } else { return input + 10; } } console.log(checkType(42));
Attempts:
2 left
💡 Hint
Think about what happens when input is a number and you add 10.
✗ Incorrect
The function checks if input is a string. Since 42 is a number, it adds 10 to it, resulting in 52.
❓ Predict Output
intermediate2:00remaining
Type narrowing effect on union types
What will this code output when
value = true?Typescript
function process(value: string | boolean) { if (typeof value === 'boolean') { return value ? 'Yes' : 'No'; } else { return value.length; } } console.log(process(true));
Attempts:
2 left
💡 Hint
Check the typeof condition and what happens for booleans.
✗ Incorrect
Since value is boolean true, the function returns 'Yes'.
🔧 Debug
advanced2:00remaining
Identify the runtime error caused by incorrect type narrowing
What error does this code produce when
data = 123?Typescript
function formatData(data: string | number) { if (typeof data === 'string') { return data.trim(); } else if (typeof data === 'number') { return data.toFixed(2); } return data; } console.log(formatData(123));
Attempts:
2 left
💡 Hint
Check the typeof checks and methods called on each type.
✗ Incorrect
The code correctly narrows the type and calls toFixed on number 123, outputting '123.00'.
❓ Predict Output
advanced2:00remaining
Output when typeof narrowing misses a case
What is the output of this code when
input = null?Typescript
function checkInput(input: string | null) { if (typeof input === 'string') { return input.length; } else { return 'No string'; } } console.log(checkInput(null));
Attempts:
2 left
💡 Hint
Remember typeof null is 'object', not 'string'.
✗ Incorrect
Since input is null, typeof input is 'object', so the else branch runs returning 'No string'.
🧠 Conceptual
expert2:00remaining
Why typeof narrowing is safer than direct property access
Why is using
typeof to narrow types safer than directly accessing properties without checks in TypeScript?Attempts:
2 left
💡 Hint
Think about what happens if you try to call a string method on a number.
✗ Incorrect
Using typeof ensures the code only accesses properties or methods valid for that type, avoiding runtime errors.