Documentation Index
Fetch the complete documentation index at: https://mintlify.com/typescript-exercises/typescript-exercises/llms.txt
Use this file to discover all available pages before exploring further.
Exercise 3: Type Narrowing with the in Operator
Scenario
You want to display additional information for each person - occupation for Users and role for Admins. However, TypeScript won’t let you access these properties directly on a union type.The Problem
Key Concepts
Type Narrowing
The process of refining a union type to a more specific type
in Operator
Checks if a property exists on an object, narrowing the type accordingly
Understanding the in Operator
The in operator is a type guard that checks for property existence:
Solution
- Problem
- Solution
Why the Original Code Fails
What's wrong with if (person.role)?
What's wrong with if (person.role)?
The check
if (person.role) tries to access the role property before checking if it exists. TypeScript doesn’t allow this on union types because:personcould be aUser, which doesn’t haverole- The property access itself would cause a compile error
in operator checks for property existence without accessing it, allowing TypeScript to narrow the type safely.How Type Narrowing Works
Alternative Type Guards
While thein operator works well here, TypeScript offers other type narrowing techniques:
You’ll learn about type predicates in the next exercise, which provide even more control over type narrowing.
Common Pitfalls
Real-World Example
What You Learned
The in Operator
The in Operator
Use
'property' in object to check for property existence and narrow typesControl Flow Analysis
Control Flow Analysis
TypeScript tracks type narrowing through if/else branches automatically
Type Safety
Type Safety
Type guards prevent runtime errors by ensuring properties exist before access