Object type annotation inline in Typescript - Time & Space 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?
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 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.
As the number of properties in the object grows, the number of operations remains constant (always 3 accesses).
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 |
| 10 | 3 |
| 100 | 3 |
Pattern observation: The work stays constant regardless of the number of properties since only specific named properties are accessed.
Time Complexity: O(1)
This means the time to run remains constant as the number of object properties increases.
[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.
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.
"What if the function processed an array of such objects instead of just one? How would the time complexity change?"