Optional properties in interfaces
📖 Scenario: You are building a simple contact list app. Each contact has a name and a phone number. Sometimes, a contact might also have an email address, but not always.
🎯 Goal: Create a TypeScript interface with optional properties to represent contacts. Then create a few contacts using this interface and print their details.
📋 What You'll Learn
Create an interface called
Contact with properties name (string), phone (string), and an optional email (string).Create a variable called
contacts which is an array of Contact objects.Add three contacts to the
contacts array. At least one contact should have an email, and at least one should not.Use a
for loop to print each contact's name, phone, and email if it exists.💡 Why This Matters
🌍 Real World
Optional properties are common when some data might be missing or not required, like user profiles or settings.
💼 Career
Understanding optional properties helps you write flexible and safe TypeScript code, a key skill for frontend and backend development.
Progress0 / 4 steps