Duck typing mental model in TypeScript - Time & Space Complexity
We want to see how the time it takes to check if an object fits a type grows as the object gets bigger.
How does TypeScript's duck typing affect the time it takes to verify an object's shape?
Analyze the time complexity of the following code snippet.
interface Bird {
fly(): void;
sing(): void;
}
function canFly(bird: any): bird is Bird {
return typeof bird.fly === 'function' && typeof bird.sing === 'function';
}
const obj = {
fly() { console.log('Flying'); },
sing() { console.log('Singing'); },
walk() { console.log('Walking'); }
};
canFly(obj);
This code checks if an object has the methods needed to be considered a Bird by looking at its properties.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each required property on the object.
- How many times: Once per property checked (here, two properties: fly and sing).
As the number of properties to check grows, the time to verify grows linearly.
| Input Size (number of properties) | Approx. Operations |
|---|---|
| 2 | 2 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The time grows directly with the number of properties checked.
Time Complexity: O(n)
This means the time to check the object's shape grows in a straight line as the number of properties to check increases.
[X] Wrong: "Checking one property means constant time no matter how many properties the object has."
[OK] Correct: Even if the object is large, you must check each required property one by one, so more properties mean more checks and more time.
Understanding how duck typing checks scale helps you explain how TypeScript verifies types behind the scenes, showing your grasp of both coding and performance.
"What if we added nested objects to check inside the main object? How would the time complexity change?"