Recall & Review
beginner
What is type narrowing in TypeScript?
Type narrowing is the process where TypeScript reduces a variable's possible types to a more specific one based on checks or conditions in the code.
Click to reveal answer
beginner
Why do we need type narrowing in TypeScript?
We need type narrowing to safely access properties or methods of a variable when it can have multiple types, preventing errors and improving code safety.
Click to reveal answer
intermediate
How does type narrowing help prevent runtime errors?
By checking a variable's type before using it, TypeScript ensures only valid operations run, avoiding errors like calling a method on an undefined or wrong type.
Click to reveal answer
beginner
Give an example of a type narrowing check in TypeScript.
Using an if statement like
if (typeof value === 'string') narrows the type of value to string inside the block.Click to reveal answer
intermediate
What happens if you don't use type narrowing when needed?
Without narrowing, TypeScript may show errors or allow unsafe code that can cause bugs or crashes when the program runs.
Click to reveal answer
What does type narrowing do in TypeScript?
✗ Incorrect
Type narrowing makes the variable's type more specific after checking conditions.
Why is type narrowing important?
✗ Incorrect
Type narrowing helps avoid errors by confirming the variable's type before use.
Which of these is a common way to narrow types?
✗ Incorrect
Using if statements with typeof or instanceof checks narrows types safely.
What happens if you try to access a property without narrowing a union type?
✗ Incorrect
TypeScript prevents unsafe access by showing errors if types are not narrowed.
Which keyword helps TypeScript narrow types inside a condition?
✗ Incorrect
The typeof operator is used to check and narrow primitive types.
Explain why type narrowing is needed in TypeScript and how it improves code safety.
Think about what happens when a variable can be many types.
You got /4 concepts.
Describe a simple example of type narrowing using an if statement in TypeScript.
Use typeof to check if a variable is a string or number.
You got /4 concepts.