0
0
Typescriptprogramming~15 mins

The in operator narrowing in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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 type
Print 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
1
Create the vehicle types and a variable
Create two types called Car and Bike. Car should have a property doors of type number. Bike should have a property hasPedals of type boolean. Then create a variable called vehicle of type Car | Bike and assign it the value { doors: 4 }.
Typescript
Need a hint?

Use type keyword to create types. Use | to combine types for the variable.

2
Add a check using the in operator
Add an if statement that checks if the property doors is in vehicle using the in operator.
Typescript
Need a hint?

Use if ('doors' in vehicle) to check if the vehicle has the doors property.

3
Access the property inside the if block
Inside the if block, create a variable called doorCount and set it to vehicle.doors.
Typescript
Need a hint?

Inside the if block, use let doorCount = vehicle.doors; to access the property.

4
Print the door count
Add a console.log statement inside the if block to print doorCount.
Typescript
Need a hint?

Use console.log(doorCount); to print the number of doors.