What structural typing means in Typescript - Time & Space Complexity
We want to understand how the cost of checking types grows when using structural typing in TypeScript.
How does the program decide if two types match as the size of the types grows?
Analyze the time complexity of comparing two object types structurally.
function areTypesCompatible(a: object, b: object): boolean {
for (const key in a) {
if (!(key in b)) return false;
}
return true;
}
This code checks if all keys in object a exist in object b, a simple structural type check.
Look at what repeats when comparing types.
- Primary operation: Looping over all keys in object
a. - How many times: Once for each key in
a.
As the number of keys in a grows, the number of checks grows the same way.
| Input Size (n keys in a) | Approx. Operations |
|---|---|
| 10 | About 10 key checks |
| 100 | About 100 key checks |
| 1000 | About 1000 key checks |
Pattern observation: The work grows directly with the number of keys in the first object.
Time Complexity: O(n)
This means the time to check grows in a straight line with the number of keys we compare.
[X] Wrong: "Checking types is instant no matter how big the objects are."
[OK] Correct: The program must look at each key to be sure, so more keys mean more work.
Understanding how structural typing checks scale helps you explain how TypeScript works behind the scenes and shows you think about efficiency in real code.
"What if we also checked that the values for each key have compatible types? How would the time complexity change?"