Keyof operator in Typescript - Time & Space Complexity
We want to understand how the time it takes to use the keyof operator changes as the size of the object grows.
Specifically, how does the work grow when we get all keys from a bigger object?
Analyze the time complexity of the following code snippet.
type Person = {
name: string;
age: number;
location: string;
};
type PersonKeys = keyof Person;
This code gets all the keys of the Person type as a union type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The compiler internally iterates over each property of the type to collect keys.
- How many times: Once for each property in the type.
As the number of properties in the type increases, the work to collect keys grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 operations (one per property) |
| 10 | 10 operations |
| 100 | 100 operations |
Pattern observation: The work grows in a straight line as the number of properties grows.
Time Complexity: O(n)
This means the time to get all keys grows directly with the number of properties in the type.
[X] Wrong: "Using keyof is instant no matter how many properties there are."
[OK] Correct: The compiler must check each property to build the keys, so more properties mean more work.
Understanding how TypeScript handles types like keyof helps you reason about code performance and compiler behavior, a useful skill in real projects.
"What if the type has nested objects? How would using keyof on nested types affect the time complexity?"