0
0
Typescriptprogramming~5 mins

Custom type guard functions in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom type guard functions
O(n)
Understanding Time Complexity

We want to understand how the time it takes to check types grows as we use custom type guard functions.

How does the number of checks change when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function isStringArray(value: unknown): value is string[] {
  return Array.isArray(value) && value.every(item => typeof item === 'string');
}

const data = ['apple', 'banana', 'cherry'];
const result = isStringArray(data);
    

This code checks if a value is an array of strings by testing each item.

Identify Repeating Operations
  • Primary operation: The every method loops through each item in the array.
  • How many times: It runs once for each element in the input array.
How Execution Grows With Input

As the array gets bigger, the number of checks grows in a straight line.

Input Size (n)Approx. Operations
1010 type checks
100100 type checks
10001000 type checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to check grows in direct proportion to the number of items in the array.

Common Mistake

[X] Wrong: "The type guard runs in constant time no matter the array size."

[OK] Correct: Because it checks each item one by one, the time grows as the array grows.

Interview Connect

Understanding how type guards scale helps you write efficient checks and shows you think about performance in real code.

Self-Check

What if the type guard also checked nested arrays inside the main array? How would the time complexity change?