0
0
Typescriptprogramming~15 mins

Optional properties in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional properties
📖 Scenario: You are creating a simple contact list app. Some contacts have a phone number, but some do not.
🎯 Goal: Learn how to define and use optional properties in TypeScript interfaces.
📋 What You'll Learn
Create an interface with optional properties
Create objects using that interface
Access optional properties safely
💡 Why This Matters
🌍 Real World
Many real-world apps store user or contact information where some details may be missing. Optional properties let you model this clearly.
💼 Career
Understanding optional properties is important for writing robust TypeScript code in web development, especially when working with APIs or user data.
Progress0 / 4 steps
1
Create an interface with optional properties
Create an interface called Contact with two properties: name of type string and an optional property phone of type string. Use the ? symbol to mark phone as optional.
Typescript
Need a hint?

Use phone?: string to make the phone property optional.

2
Create contact objects using the interface
Create two variables called contact1 and contact2 of type Contact. Set contact1 to have name as "Alice" and phone as "123-4567". Set contact2 to have name as "Bob" without a phone property.
Typescript
Need a hint?

Remember to omit the phone property for contact2.

3
Check and use optional properties
Write a function called printContact that takes a Contact parameter called contact. Inside the function, use an if statement to check if contact.phone exists. If it does, print "Name: " plus the name and "Phone: " plus the phone. Otherwise, print "Name: " plus the name and "Phone: Not available".
Typescript
Need a hint?

Use if (contact.phone) to check if the phone exists.

4
Print contact details
Call printContact with contact1 and then with contact2 to display their details.
Typescript
Need a hint?

Call printContact(contact1) and printContact(contact2).