0
0
Typescriptprogramming~5 mins

Why type narrowing is needed in Typescript - Quick Recap

Choose your learning style9 modes available
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?
ARemoves types from variables
BChanges the variable's value automatically
CConverts all types to string
DMakes a variable's type more specific based on checks
Why is type narrowing important?
ATo convert types to numbers
BTo make code run faster
CTo prevent runtime errors by ensuring safe operations
DTo hide errors from the developer
Which of these is a common way to narrow types?
AUsing if statements with typeof checks
BUsing console.log statements
CDeclaring variables without types
DIgnoring type errors
What happens if you try to access a property without narrowing a union type?
AThe code always works fine
BTypeScript shows an error or warning
CThe property is ignored
DThe variable changes type automatically
Which keyword helps TypeScript narrow types inside a condition?
Atypeof
Bvar
Cfunction
Dclass
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.