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?"