Indexed access types in Typescript - Time & Space 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?
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 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').
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) |
|---|---|
| 1 | 1 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The work grows directly with the number of keys accessed.
Time Complexity: O(n)
This means the time to resolve the indexed access type grows linearly with the number of keys in the union.
[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.
Understanding how type operations scale helps you reason about code maintainability and performance in TypeScript projects.
"What if we changed the union of keys to a single key type? How would the time complexity change?"