Extract type in Typescript - Time & Space Complexity
Let's see how the time it takes to run code using the Extract type changes as the input grows.
We want to know how the work done scales when extracting types from bigger sets.
Analyze the time complexity of the following code snippet.
type Extract<T, U> = T extends U ? T : never;
// Example usage:
type Result = Extract<'a' | 'b' | 'c', 'a' | 'c'>;
// Result is 'a' | 'c'
This code picks types from T that are assignable to U, filtering the union types.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each member of the union type T against U.
- How many times: Once for each member in the union T.
Each additional type in T means one more check against U.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of types in T.
Time Complexity: O(n)
This means the time to extract types grows linearly with the number of types in the input.
[X] Wrong: "Extract type runs instantly no matter how many types are in the union."
[OK] Correct: Each type in the union must be checked, so more types mean more work.
Understanding how type operations scale helps you reason about code performance and complexity in real projects.
"What if we changed the Extract type to check against multiple types in U? How would the time complexity change?"