Omit type in Typescript - Time & Space Complexity
We want to understand how the time to create a new type by removing some keys grows as the original type gets bigger.
How does the work change when we omit more properties from a type?
Analyze the time complexity of the following code snippet.
type Omit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
};
interface Person {
name: string;
age: number;
location: string;
}
// Using Omit to remove 'age'
type PersonWithoutAge = Omit<Person, 'age'>;
This code creates a new type by removing certain keys from an existing type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each key in the original type.
- How many times: Once for each key in the type.
As the number of keys in the original type grows, the time to create the omitted type grows in a similar way.
| Input Size (number of keys) | Approx. Operations |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The work grows directly with the number of keys in the original type.
Time Complexity: O(n)
This means the time to create the new type grows linearly with the number of keys in the original type.
[X] Wrong: "Omitting keys is instant and does not depend on the number of keys."
[OK] Correct: The process checks each key to decide if it should be included, so more keys mean more work.
Understanding how type operations scale helps you reason about code complexity and performance in real projects.
What if we changed the Omit type to remove multiple keys at once? How would the time complexity change?