Using the in Operator for Type Narrowing in TypeScript
📖 Scenario: You are building a simple program that handles different types of vehicles. Each vehicle type has unique properties. You want to safely check which type of vehicle you have and access its specific properties.
🎯 Goal: Learn how to use the in operator in TypeScript to narrow down types and safely access properties that only exist on certain types.
📋 What You'll Learn
Create a union type with two vehicle types
Create a variable with one of the vehicle types
Use the
in operator to check the typePrint the specific property based on the type
💡 Why This Matters
🌍 Real World
In real apps, you often work with data that can be one of many types. Using the <code>in</code> operator helps you safely check which type you have and avoid errors.
💼 Career
Understanding type narrowing with the <code>in</code> operator is important for writing safe and clear TypeScript code, a skill valued in frontend and backend development jobs.
Progress0 / 4 steps