0
0
Typescriptprogramming~20 mins

Why type narrowing is needed in Typescript - Challenge Your Understanding

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
What is the output of this TypeScript code with type narrowing?

Look at the code below. What will it print when run?

Typescript
function printLength(x: string | number) {
  if (typeof x === 'string') {
    console.log(x.length);
  } else {
    console.log(x.toFixed(2));
  }
}
printLength('hello');
printLength(3.14159);
A5 and 3.14
Bundefined and 3.14
C5 and 3.14159
DError at compile time
Attempts:
2 left
💡 Hint

Think about how TypeScript knows what methods are safe to call on x.

🧠 Conceptual
intermediate
1:30remaining
Why do we need type narrowing in TypeScript?

Choose the best reason why type narrowing is important in TypeScript.

ATo allow calling properties or methods safely on union types by knowing the exact type at runtime
BTo make the code run faster by removing type checks
CTo convert all types to strings automatically
DTo disable type checking for certain variables
Attempts:
2 left
💡 Hint

Think about how TypeScript prevents errors when a variable can be more than one type.

🔧 Debug
advanced
1:30remaining
What error does this TypeScript code raise without type narrowing?

Look at this code. What error will TypeScript show?

Typescript
function doubleValue(x: string | number) {
  return x * 2;
}
AError: Missing return statement
BNo error, returns doubled value for both types
CError: Operator '*' cannot be applied to types 'string | number' and 'number'.
DError: Cannot multiply by 2
Attempts:
2 left
💡 Hint

Think about what happens when you try to multiply a string by a number in TypeScript.

📝 Syntax
advanced
2:00remaining
Which option correctly narrows the type to string in this code?

Choose the correct way to narrow the type of value to string before calling toUpperCase().

Typescript
function shout(value: string | number) {
  // Narrow value to string here
  console.log(value.toUpperCase());
}
Aif (value instanceof String) { console.log(value.toUpperCase()); }
Bif (value === 'string') { console.log(value.toUpperCase()); }
Cif (typeof value === 'number') { console.log(value.toUpperCase()); }
Dif (typeof value === 'string') { console.log(value.toUpperCase()); }
Attempts:
2 left
💡 Hint

Remember how to check the type of a variable in JavaScript/TypeScript.

🚀 Application
expert
2:30remaining
What is the output of this TypeScript code using type narrowing with custom type guard?

Consider this code with a custom type guard function. What will it print?

Typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    return 'Fish swims';
  } else {
    return 'Bird flies';
  }
}

console.log(move({ swim: () => {} }));
console.log(move({ fly: () => {} }));
A"Bird flies" followed by "Fish swims"
B"Fish swims" followed by "Bird flies"
CRuntime error because of wrong type assertion
DBoth calls return "Fish swims"
Attempts:
2 left
💡 Hint

Look at how the custom type guard works and what it checks.