Optional properties in Typescript - Time & Space Complexity
We want to see how the time to run code changes when using optional properties in TypeScript objects.
Specifically, does checking or using optional properties affect how long the code takes as input grows?
Analyze the time complexity of the following code snippet.
interface User {
id: number;
name: string;
age?: number; // optional property
}
function printUserAges(users: User[]) {
for (const user of users) {
if (user.age !== undefined) {
console.log(`${user.name} is ${user.age} years old.`);
}
}
}
This code loops through a list of users and prints their age only if the age property exists.
- Primary operation: Looping through each user in the array.
- How many times: Once for every user in the list.
As the number of users grows, the code checks each user once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and possible prints |
| 100 | About 100 checks and possible prints |
| 1000 | About 1000 checks and possible prints |
Pattern observation: The work grows directly with the number of users.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of users.
[X] Wrong: "Checking optional properties makes the code slower in a big way."
[OK] Correct: Checking if a property exists is a simple step done once per item, so it does not add extra loops or big delays.
Understanding how optional properties affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we changed the code to print all user properties, including optional ones, without checking if they exist? How would the time complexity change?"
Practice
? symbol mean when used in a TypeScript interface property like age?: number?Solution
Step 1: Understand the meaning of
The?in interfaces?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 CQuick Check:
Optional property = property with?[OK]
? to spot optional properties quickly [OK]- Thinking
?means property is required - Confusing optional with readonly or private
- Assuming optional properties must have a default value
email of type string in a TypeScript interface?Solution
Step 1: Recall TypeScript optional property syntax
Optional properties use a?immediately after the property name, before the colon and type.Step 2: Check each option
email?: string matches the correct syntax:email?: string. Others are invalid syntax.Final Answer:
email?: string -> Option AQuick Check:
Optional property syntax = name + ? + : + type [OK]
? goes right after property name [OK]- Placing
?after the type instead of property name - Using keywords like 'optional' which are invalid
- Missing colon between property name and type
interface User {
id: number;
name?: string;
}
const user: User = { id: 1 };
console.log(user.name);What will be the output when running this code?
Solution
Step 1: Understand optional property behavior
The propertynameis optional and not provided in the object, so it is undefined.Step 2: Check console.log output
Logginguser.nameprintsundefinedbecause the property is missing, not null or empty string.Final Answer:
undefined -> Option AQuick Check:
Missing optional property = undefined [OK]
- Expecting runtime error for missing optional property
- Confusing undefined with null or empty string
- Assuming default values are assigned automatically
interface Product {
id: number;
description?: string = "No description";
}Solution
Step 1: Check interface property syntax
Interfaces only declare types; they cannot assign default values to properties.Step 2: Analyze the error
The syntaxdescription?: string = "No description"is invalid because default values are not allowed in interfaces.Final Answer:
Optional properties cannot have default values in interfaces. -> Option DQuick Check:
Interfaces declare types, no default values allowed [OK]
- Trying to assign default values inside interfaces
- Confusing interfaces with classes or object literals
- Ignoring TypeScript syntax rules for interfaces
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?
}Solution
Step 1: Understand optional property usage
ThemiddleNamemay 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 BQuick Check:
Use?? ''to safely handle optional strings [OK]
- Directly using optional property without checks
- Using non-null assertion (!) unsafely
- Concatenating without spaces or trimming
Ready to prove it?
Pass the test and this pattern moves unknown
