📖 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
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
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
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
Hint
Call printContact(contact1) and printContact(contact2).
Practice
(1/5)
1. What does the ? symbol mean when used in a TypeScript interface property like age?: number?
easy
A. The property is required and must always be present.
B. The property is private and cannot be accessed outside the interface.
C. The property is optional and may or may not be present in objects.
D. The property is readonly and cannot be changed after initialization.
Solution
Step 1: Understand the meaning of ? in interfaces
The ? after a property name marks it as optional, meaning it can be missing in objects that implement the interface.
Step 2: Compare with other property types
Required properties must always be present, private and readonly are unrelated concepts.
Final Answer:
The property is optional and may or may not be present in objects. -> Option C
Quick Check:
Optional property = property with ? [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 a default value
2. Which of the following is the correct syntax to declare an optional property email of type string in a TypeScript interface?
D. Optional properties cannot have default values in interfaces.
Solution
Step 1: Check interface property syntax
Interfaces only declare types; they cannot assign default values to properties.
Step 2: Analyze the error
The syntax description?: string = "No description" is invalid because default values are not allowed in interfaces.
Final Answer:
Optional properties cannot have default values in interfaces. -> Option D
Quick Check:
Interfaces declare types, no default values allowed [OK]
Hint: Interfaces declare types only, no default values [OK]
Common Mistakes:
Trying to assign default values inside interfaces
Confusing interfaces with classes or object literals
Ignoring TypeScript syntax rules for interfaces
5. You want to create a function that accepts an object with optional middleName property and returns the full name. Which of these implementations correctly handles the optional property without errors?
interface Person {
firstName: string;
middleName?: string;
lastName: string;
}
function getFullName(person: Person): string {
// Which code below is correct?
}
hard
A. return `${person.firstName} ${person.middleName} ${person.lastName}`;
B. return `${person.firstName} ${person.middleName ?? ''} ${person.lastName}`.trim();
C. return `${person.firstName} ${person.middleName!} ${person.lastName}`;
D. return person.firstName + person.middleName + person.lastName;
Solution
Step 1: Understand optional property usage
The middleName may be undefined, so accessing it directly can cause unwanted 'undefined' in output.
Step 2: Evaluate each option
return `${person.firstName} ${person.middleName} ${person.lastName}`; inserts undefined if missing. return `${person.firstName} ${person.middleName ?? ''} ${person.lastName}`.trim(); uses nullish coalescing ?? to replace undefined with empty string and trims extra spaces. return `${person.firstName} ${person.middleName!} ${person.lastName}`; uses non-null assertion which can cause runtime errors if missing. return person.firstName + person.middleName + person.lastName; concatenates without spaces and can produce 'undefined' string.
Final Answer:
return `${person.firstName} ${person.middleName ?? ''} ${person.lastName}`.trim(); -> Option B
Quick Check:
Use ?? '' to safely handle optional strings [OK]
Hint: Use nullish coalescing (?? '') to handle optional strings safely [OK]
Common Mistakes:
Directly using optional property without checks
Using non-null assertion (!) unsafely
Concatenating without spaces or trimming
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.