0
0
Typescriptprogramming~5 mins

Optional properties in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Optional properties
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each user in the array.
  • How many times: Once for every user in the list.
How Execution Grows With Input

As the number of users grows, the code checks each user once.

Input Size (n)Approx. Operations
10About 10 checks and possible prints
100About 100 checks and possible prints
1000About 1000 checks and possible prints

Pattern observation: The work grows directly with the number of users.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of users.

Common Mistake

[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.

Interview Connect

Understanding how optional properties affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

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