0
0
Typescriptprogramming~5 mins

Object type annotation inline in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object type annotation inline
O(1)
Understanding Time Complexity

When we write object type annotations inline in TypeScript, we want to know how this affects the time it takes for the program to run.

We ask: How does the program's work grow as the object size or usage grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function printUser(user: { name: string; age: number; active: boolean }) {
  console.log(`Name: ${user.name}`);
  console.log(`Age: ${user.age}`);
  console.log(`Active: ${user.active}`);
}

const user = { name: "Alice", age: 30, active: true };
printUser(user);
    

This code defines a function with an inline object type annotation and prints its properties.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing and printing each property of the object once.
  • How many times: Exactly three times, once per property.
How Execution Grows With Input

As the number of properties in the object grows, the number of operations remains constant (always 3 accesses).

Input Size (n)Approx. Operations
33
103
1003

Pattern observation: The work stays constant regardless of the number of properties since only specific named properties are accessed.

Final Time Complexity

Time Complexity: O(1)

This means the time to run remains constant as the number of object properties increases.

Common Mistake

[X] Wrong: "Using inline object type annotations makes the code slower because it adds extra work at runtime."

[OK] Correct: Type annotations are only for the developer and compiler; they do not affect the running speed of the program.

Interview Connect

Understanding how your code scales with input size helps you write clear and efficient programs, a skill valued in many coding challenges and real projects.

Self-Check

"What if the function processed an array of such objects instead of just one? How would the time complexity change?"