Mapped type with conditional types in Typescript - Time & Space 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?
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 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.
As the number of properties in T grows, the number of checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of properties, one check per property.
Time Complexity: O(n)
This means the time to create the mapped type grows linearly with the number of properties in the input type.
[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.
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.
"What if we nested another mapped type inside this one? How would the time complexity change?"