0
0
Typescriptprogramming~5 mins

Excess property checks vs structural compatibility in Typescript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Excess property checks vs structural compatibility
O(n)
Understanding Time Complexity

We want to understand how TypeScript checks object properties affect performance.

Specifically, how excess property checks and structural compatibility scale with input size.

Scenario Under Consideration

Analyze the time complexity of this TypeScript code snippet.


interface Person {
  name: string;
  age: number;
}

const p1: Person = { name: "Alice", age: 30 };
const p2: Person = { name: "Bob", age: 25, city: "NY" };

function greet(person: Person) {
  console.log(`Hello, ${person.name}`);
}

greet(p1);
greet(p2); // Error: excess property 'city'
    

This code shows how TypeScript checks for extra properties when assigning objects to a type.

Identify Repeating Operations
  • Primary operation: Checking each property of the object against the expected type properties.
  • How many times: Once per property in the object being assigned.
How Execution Grows With Input

As the number of properties in the object grows, the number of checks grows too.

Input Size (number of properties)Approx. Operations (property checks)
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The number of checks grows directly with the number of properties.

Final Time Complexity

Time Complexity: O(n)

This means the checking time grows linearly with the number of properties in the object.

Common Mistake

[X] Wrong: "Excess property checks happen instantly no matter how many properties there are."

[OK] Correct: Each property must be checked, so more properties mean more work for the compiler.

Interview Connect

Understanding how TypeScript checks object shapes helps you write better code and reason about performance.

Self-Check

"What if we passed an object with nested objects? How would the time complexity change?"