📖 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
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
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
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
Hint
Use an if statement to check if contact.email exists before printing it.
Practice
(1/5)
1. What does the ? symbol mean when used in a TypeScript interface property like age?: number?
easy
A. The property is readonly and cannot be changed after initialization.
B. The property is required and must always be provided.
C. The property is private and cannot be accessed outside the interface.
D. The property is optional and may be omitted when creating an object.
Solution
Step 1: Understand the ? in interface properties
The ? after a property name in an interface means that property is optional.
Step 2: Effect on object creation
This means when creating an object of that interface type, you can omit that property without error.
Final Answer:
The property is optional and may be omitted when creating an object. -> Option D
Quick Check:
Optional property = may be omitted [OK]
Hint: Look for ? to spot optional properties quickly [OK]
Common Mistakes:
Thinking ? means property is required
Confusing optional with readonly or private
Assuming optional properties must have default values
2. Which of the following is the correct syntax to declare an optional property email of type string in a TypeScript interface?
easy
A. email: string;
B. email: string?;
C. email?: string;
D. optional email: string;
Solution
Step 1: Recall optional property syntax
In TypeScript, optional properties use a ? immediately after the property name.
Step 2: Match syntax to options
Only email?: string; uses email?: string; which is correct syntax for optional property.
Final Answer:
email?: string; -> Option C
Quick Check:
Optional property syntax = name? : type [OK]
Hint: Remember: ? goes right after property name [OK]
Common Mistakes:
Placing ? after the type instead of property name
Using keywords like 'optional' which are invalid
Omitting the semicolon but that is less critical
3. Given the interface and object below, what will be the output of console.log(user.age)?
interface User {
name: string;
age?: number;
}
const user: User = { name: "Alice" };
console.log(user.age);
medium
A. Error: Property 'age' is missing
B. undefined
C. null
D. 0
Solution
Step 1: Understand optional property behavior
The property age is optional and not provided in the object.
Step 2: Check value of missing optional property
Accessing a missing optional property returns undefined in JavaScript/TypeScript.
Final Answer:
undefined -> Option B
Quick Check:
Missing optional property = undefined [OK]
Hint: Missing optional property returns undefined, not error [OK]
Common Mistakes:
Expecting runtime error for missing optional property
Confusing undefined with null or zero
Assuming default values are assigned automatically
4. Identify the error in the following code snippet:
Which of the following objects correctly implements Config with only url provided and no errors?
hard
A. { url: "http://example.com", timeout: undefined, retries: undefined }
B. { url: "http://example.com", timeout: null }
C. { url: "http://example.com", timeout: 0, retries: 3 }
D. { timeout: 1000, retries: 3 }
Solution
Step 1: Check required properties
The url property is required and must be present.
Step 2: Validate optional properties usage
Optional properties can be omitted or set to undefined without error.
Step 3: Analyze each option
{ url: "http://example.com", timeout: undefined, retries: undefined } has url and optional properties set to undefined, which is valid. { url: "http://example.com", timeout: null } uses null which is not assignable to number. { url: "http://example.com", timeout: 0, retries: 3 } includes optional properties but that is allowed, but question asks for only url provided. { timeout: 1000, retries: 3 } misses required url property.