0
0
Typescriptprogramming~5 mins

Mapped type with conditional types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Mapped type with conditional types
O(n)
Understanding Time Complexity

We want to understand how the time needed to create a new type changes as the input type grows.

How does the process of mapping and checking conditions for each property scale?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


type FilterStrings<T> = {
  [K in keyof T]: T[K] extends string ? K : never
}[keyof T];

// This creates a union of keys whose values are strings
    

This code creates a new type by checking each property of T and keeping only those keys whose values are strings.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Iterating over each key in the input type T.
  • How many times: Once for every property key in T.
How Execution Grows With Input

As the number of properties in T grows, the number of checks grows the same way.

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

Pattern observation: The work grows directly with the number of properties, one check per property.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the mapped type grows linearly with the number of properties in the input type.

Common Mistake

[X] Wrong: "The conditional check inside the mapped type runs multiple times per property or grows faster than the number of properties."

[OK] Correct: Each property is checked exactly once, so the total work grows only with the number of properties, not more.

Interview Connect

Understanding how mapped types with conditions scale helps you reason about type transformations and their cost, a useful skill for writing efficient and maintainable TypeScript code.

Self-Check

"What if we nested another mapped type inside this one? How would the time complexity change?"