0
0
Typescriptprogramming~5 mins

Type predicates in practice in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type predicates in practice
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code with type predicates changes as input grows.

How does checking types affect the speed when we have many items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function filterStrings(items: unknown[]): string[] {
  return items.filter(isString);
}
    

This code filters an array to keep only strings using a type predicate function.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The filter method loops through each item in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 type checks
100About 100 type checks
1000About 1000 type checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to filter grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Using a type predicate makes the filtering slower than normal because it adds extra checks."

[OK] Correct: The type predicate is just a simple check done once per item, so it does not add extra loops or nested work. The main cost is still just going through the list once.

Interview Connect

Understanding how type checks affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.

Self-Check

"What if we changed the filter to check two different type predicates for each item? How would the time complexity change?"