Excess property checks vs structural compatibility in Typescript - Performance Comparison
We want to understand how TypeScript checks object properties affect performance.
Specifically, how excess property checks and structural compatibility scale with input size.
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.
- Primary operation: Checking each property of the object against the expected type properties.
- How many times: Once per property in the object being assigned.
As the number of properties in the object grows, the number of checks grows too.
| Input Size (number of properties) | Approx. Operations (property checks) |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the number of properties.
Time Complexity: O(n)
This means the checking time grows linearly with the number of properties in the object.
[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.
Understanding how TypeScript checks object shapes helps you write better code and reason about performance.
"What if we passed an object with nested objects? How would the time complexity change?"