Recall & Review
beginner
What does the
in operator do in TypeScript type narrowing?It checks if a property exists in an object and narrows the type based on that check.
Click to reveal answer
beginner
How does TypeScript narrow types using
if ('property' in object)?Inside the
if block, TypeScript knows the object has that property, so it narrows the type to those that include that property.Click to reveal answer
intermediate
Given
type A = {x: number} and type B = {y: string}, what does if ('x' in obj) narrow obj to?It narrows
obj to type A because only A has the property x.Click to reveal answer
intermediate
Can the
in operator be used to narrow union types with overlapping properties?Yes, but if both types have the property,
in won't narrow the type because the property exists in both.Click to reveal answer
beginner
Why is
in operator narrowing useful in TypeScript?It helps safely access properties by confirming they exist, preventing runtime errors and improving code safety.
Click to reveal answer
What does
if ('prop' in obj) check in TypeScript?✗ Incorrect
The
in operator checks if the property exists in the object.If
type A = {x: number} and type B = {y: string}, what does if ('x' in obj) narrow obj to?✗ Incorrect
Only type A has the property
x, so the check narrows to A.Can
in operator narrow types if both union members share the same property?✗ Incorrect
If both types have the property,
in cannot distinguish between them.What happens if you use
in operator on a property that does not exist in any union member?✗ Incorrect
The check is always false, so TypeScript narrows to never inside the block.
Why is using
in operator narrowing safer than just accessing a property directly?✗ Incorrect
Checking with
in ensures the property exists before access, avoiding errors.Explain how the
in operator helps TypeScript narrow types in a union.Think about how TypeScript knows which type you have inside an if block.
You got /3 concepts.
Describe a situation where
in operator narrowing would not work to distinguish types.Consider when two types share the same property name.
You got /3 concepts.