0
0
Typescriptprogramming~5 mins

The in operator narrowing in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIf <code>prop</code> is a function
BIf <code>obj</code> is a string
CIf <code>obj</code> is null
DIf <code>obj</code> has the property <code>prop</code>
If type A = {x: number} and type B = {y: string}, what does if ('x' in obj) narrow obj to?
AType B
BBoth A and B
CType A
DNeither A nor B
Can in operator narrow types if both union members share the same property?
ANo, because the property exists in both types
BNo, never
COnly if the property is optional
DYes, always
What happens if you use in operator on a property that does not exist in any union member?
ATypeScript throws an error
BTypeScript narrows to never
CTypeScript narrows to all union members
DTypeScript ignores the check
Why is using in operator narrowing safer than just accessing a property directly?
AIt prevents runtime errors by ensuring the property exists
BIt makes the code run faster
CIt changes the property value
DIt automatically types the property as string
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.