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?"
Practice
keyof operator do in TypeScript?Solution
Step 1: Understand the purpose of
Thekeyofkeyofoperator takes an object type and produces a union of its keys as string literal types.Step 2: Compare options with definition
Only "It creates a union type of all keys of an object type." correctly describes this behavior. The other options describe unrelated TypeScript features.Final Answer:
It creates a union type of all keys of an object type. -> Option CQuick Check:
keyof= union of keys [OK]
keyof lists keys, not values or types [OK]- Confusing
keyofwith getting values - Thinking it returns runtime keys instead of types
- Mixing it up with return type extraction
Person using keyof?Solution
Step 1: Recall correct
The correct syntax iskeyofsyntaxkeyof TypeNamewithout parentheses or dot notation.Step 2: Evaluate each option
type Keys = keyof Person; uses correct syntax. type Keys = keyof(Person); incorrectly uses parentheses. type Keys = keys<Person>; uses a non-existentkeyskeyword. type Keys = Person.keyof; uses invalid dot notation.Final Answer:
type Keys = keyof Person; -> Option DQuick Check:
Correct syntax =keyof Type[OK]
keyof TypeName without parentheses [OK]- Adding parentheses around the type
- Using dot notation like
Type.keyof - Confusing
keyofwithkeys
type Car = { make: string; model: string; year: number };
type CarKeys = keyof Car;
let key: CarKeys = 'year';
console.log(key);What is the output when this code runs?
Solution
Step 1: Understand
keyofusageCarKeysis a union of keys: 'make' | 'model' | 'year'. The variablekeyis assigned the string 'year', which is valid.Step 2: Check console output
The console logs the value ofkey, which is 'year'. No errors occur.Final Answer:
'year' -> Option AQuick Check:
Assigned key = 'year' [OK]
- Expecting runtime error for type assignment
- Confusing keys with values
- Thinking
keyofreturns values
type User = { id: number; name: string };
function getValue(obj: User, key: keyof User) {
return obj.key;
}Solution
Step 1: Analyze property access in function
The function tries to accessobj.key. Sincekeyis a variable, dot notation looks for a property literally named 'key'.Step 2: Correct property access syntax
To use a variable key, bracket notationobj[key]is required to access the dynamic property.Final Answer:
Using dot notation with variable key instead of bracket notation. -> Option AQuick Check:
Useobj[key]for dynamic keys [OK]
- Using dot notation with variable keys
- Ignoring TypeScript error messages
- Assuming
keyofis invalid
keyof? Choose the correct implementation.Solution
Step 1: Understand generic constraints with
To ensure the key is valid for the object, the key typekeyofKmust extendkeyof T. This restricts keys to valid property names.Step 2: Check return type and access
The return type should beT[K], the type of the property at keyK. Accessingobj[key]returns this value safely.Step 3: Evaluate options
function getProp(obj: T, key: K): T[K] { return obj[key]; } correctly uses generics andkeyof. function getProp<T>(obj: T, key: string): any { return obj.key; } uses string key and dot notation, which is unsafe. function getProp<T>(obj: T, key: keyof T): string { return obj[key]; } fixes key type but wrongly fixes return type to string. function getProp(obj: T, key: K): K { return obj[key]; } lacks constraint onKand returns wrong type.Final Answer:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } -> Option BQuick Check:
Generic key constrained bykeyof= safe access [OK]
K extends keyof T and return T[K] [OK]- Not constraining key type with
keyof - Using string keys without type safety
- Returning wrong or fixed types
Ready to prove it?
Pass the test and this pattern moves unknown
