Exclude type in Typescript - Time & Space Complexity
Let's see how the time needed to run code changes when we use the Exclude type in TypeScript.
We want to know how the work grows as the list of types gets bigger.
Analyze the time complexity of the following code snippet.
type Exclude<T, U> = T extends U ? never : T;
// Example usage:
type Result = Exclude<'a' | 'b' | 'c', 'a' | 'b'>;
// Result is 'c'
This code removes types from T that are also in U, leaving only types not in U.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each type in T against all types in U.
- How many times: For each type in T, it compares with types in U.
As the number of types in T and U grows, the checks increase.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 checks |
| 100 | About 10,000 checks |
| 1000 | About 1,000,000 checks |
Pattern observation: The work grows quickly as both lists get bigger, multiplying together.
Time Complexity: O(n * m)
This means the time grows by multiplying the size of the first list by the size of the second list.
[X] Wrong: "The Exclude type only checks each type once, so it is O(n)."
[OK] Correct: It actually compares each type in T with every type in U, so the work multiplies.
Understanding how type operations scale helps you reason about code performance and complexity in real projects.
What if we changed U to be a single type instead of a union? How would the time complexity change?