0
0
Typescriptprogramming~5 mins

Keyof operator in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Keyof operator
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of properties in the type increases, the work to collect keys grows proportionally.

Input Size (n)Approx. Operations
33 operations (one per property)
1010 operations
100100 operations

Pattern observation: The work grows in a straight line as the number of properties grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to get all keys grows directly with the number of properties in the type.

Common Mistake

[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.

Interview Connect

Understanding how TypeScript handles types like keyof helps you reason about code performance and compiler behavior, a useful skill in real projects.

Self-Check

"What if the type has nested objects? How would using keyof on nested types affect the time complexity?"