0
0
Typescriptprogramming~20 mins

Type narrowing with typeof in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Narrowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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));
A42
BTypeError at runtime
C52
Dundefined
Attempts:
2 left
💡 Hint
Think about what happens when input is a number and you add 10.
Predict Output
intermediate
2: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));
Atrue
BTypeError: value.length is not a function
C"true"
D"Yes"
Attempts:
2 left
💡 Hint
Check the typeof condition and what happens for booleans.
🔧 Debug
advanced
2: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));
Aundefined
B123.00
CSyntaxError
DTypeError: data.trim is not a function
Attempts:
2 left
💡 Hint
Check the typeof checks and methods called on each type.
Predict Output
advanced
2: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));
A"No string"
BTypeError: Cannot read property 'length' of null
C0
Dnull
Attempts:
2 left
💡 Hint
Remember typeof null is 'object', not 'string'.
🧠 Conceptual
expert
2: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?
ABecause typeof checks prevent runtime errors by ensuring the variable is the expected type before accessing properties or methods.
BBecause typeof changes the variable type permanently in the program.
CBecause direct property access always works regardless of type.
DBecause typeof automatically converts all types to strings.
Attempts:
2 left
💡 Hint
Think about what happens if you try to call a string method on a number.