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.