Excess property checking behavior in Typescript - Time & Space Complexity
We want to understand how TypeScript checks for extra properties in objects during assignment.
How does the time to check grow as the object gets bigger?
Analyze the time complexity of the following code snippet.
interface Person {
name: string;
age: number;
}
const person = { name: "Alice", age: 30, city: "NY" };
const p: Person = person; // Excess property check
This code assigns an object with an extra property to a typed variable, triggering excess property checking.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each property of the object against the interface properties.
- How many times: Once for each property in the object being assigned.
As the number of properties in the object grows, the checking time grows roughly the same way.
| Input Size (number of properties) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time to check grows linearly with the number of properties.
Time Complexity: O(n)
This means the checking time grows directly in proportion to the number of properties in the object.
[X] Wrong: "Excess property checking happens instantly no matter how many properties there are."
[OK] Correct: The compiler must look at each property to compare it with the interface, so more properties mean more work.
Understanding how TypeScript checks object properties helps you reason about compiler behavior and performance in real projects.
"What if the object has nested objects? How would excess property checking time complexity change?"