0
0
Typescriptprogramming~5 mins

Indexed access types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Indexed access types
O(n)
Understanding Time Complexity

We want to understand how the time it takes to access types using indexed access changes as the input grows.

Specifically, how does the cost grow when we use indexed access types in TypeScript?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


type Person = {
  name: string;
  age: number;
  location: string;
};

// Access the type of the 'age' property
type AgeType = Person['age'];

// Access the type of a union of keys
type NameOrLocation = Person['name' | 'location'];
    

This code uses indexed access types to get the type of specific properties from an object type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Type lookup for each key in the union inside the indexed access.
  • How many times: Once per key in the union type (for example, 1 for 'age', 2 for 'name' | 'location').
How Execution Grows With Input

As the number of keys in the union grows, the number of type lookups grows linearly.

Input Size (number of keys)Approx. Operations (type lookups)
11
1010
100100

Pattern observation: The work grows directly with the number of keys accessed.

Final Time Complexity

Time Complexity: O(n)

This means the time to resolve the indexed access type grows linearly with the number of keys in the union.

Common Mistake

[X] Wrong: "Indexed access types always take constant time regardless of keys."

[OK] Correct: When accessing multiple keys in a union, each key requires a separate lookup, so time grows with the number of keys.

Interview Connect

Understanding how type operations scale helps you reason about code maintainability and performance in TypeScript projects.

Self-Check

"What if we changed the union of keys to a single key type? How would the time complexity change?"