0
0
Typescriptprogramming~30 mins

Optional properties in interfaces in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Contact interface
Create an interface called Contact with properties name of type string and phone of type string. Do not add the email property yet.
Typescript
Need a hint?

Use the interface keyword and define name and phone as string properties.

2
Add the optional email property
Add an optional property email of type string to the Contact interface. Use the correct syntax to make it optional.
Typescript
Need a hint?

Add a question mark ? after email to make it optional.

3
Create contacts array with some emails
Create a variable called contacts as an array of Contact. Add three contacts: one with email, one without, and one with email. Use the exact names and phones: {name: 'Alice', phone: '123-4567', email: 'alice@example.com'}, {name: 'Bob', phone: '987-6543'}, {name: 'Charlie', phone: '555-0000', email: 'charlie@example.com'}.
Typescript
Need a hint?

Use an array of objects matching the Contact interface. Remember to include the optional email only for some contacts.

4
Print contact details with optional email
Use a for loop with variables contact to iterate over contacts. Inside the loop, print the name and phone. If email exists, print it too. Use console.log and a template string to format: Name: Alice, Phone: 123-4567, Email: alice@example.com or omit Email if missing.
Typescript
Need a hint?

Use an if statement to check if contact.email exists before printing it.