0
0
Typescriptprogramming~5 mins

Duck typing mental model in TypeScript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Duck typing mental model in TypeScript
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of properties to check grows, the time to verify grows linearly.

Input Size (number of properties)Approx. Operations
22 checks
1010 checks
100100 checks

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

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how duck typing checks scale helps you explain how TypeScript verifies types behind the scenes, showing your grasp of both coding and performance.

Self-Check

"What if we added nested objects to check inside the main object? How would the time complexity change?"