0
0
Typescriptprogramming~15 mins

Optional chaining with types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional chaining with types
📖 Scenario: Imagine you have a list of users, and each user may or may not have a profile with an address. You want to safely get the city name without causing errors if some data is missing.
🎯 Goal: Build a TypeScript program that uses optional chaining to safely access nested properties in user objects.
📋 What You'll Learn
Create an array of user objects with optional nested properties
Add a variable to hold the index of the user to check
Use optional chaining to access the city name safely
Print the city name or 'Unknown' if it does not exist
💡 Why This Matters
🌍 Real World
Optional chaining helps avoid errors when working with data that may be incomplete or missing, such as user profiles or API responses.
💼 Career
Many jobs require handling uncertain data safely in TypeScript, making optional chaining a valuable skill for frontend and backend developers.
Progress0 / 4 steps
1
Create the users array with optional nested properties
Create a constant array called users with these exact objects:
1. { id: 1, profile: { address: { city: 'New York' } } }
2. { id: 2 }
3. { id: 3, profile: { address: { city: 'Los Angeles' } } }
Typescript
Need a hint?

Use const users = [ ... ] and include the exact objects with nested properties as shown.

2
Add a variable for the user index
Create a constant called userIndex and set it to 1 to select the second user.
Typescript
Need a hint?

Use const userIndex = 1; to pick the second user in the array.

3
Use optional chaining to get the city name
Create a constant called city and set it to the city name of the user at userIndex using optional chaining: users[userIndex]?.profile?.address?.city.
Typescript
Need a hint?

Use ?. to safely access nested properties without errors if any part is missing.

4
Print the city or 'Unknown' if missing
Write a console.log statement to print the value of city if it exists, or the string 'Unknown' if city is undefined.
Typescript
Need a hint?

Use the nullish coalescing operator ?? to provide a default value when city is undefined.