Index signatures for dynamic keys in Typescript - Time & Space Complexity
When using index signatures for dynamic keys, we want to know how the time to access or update data changes as the number of keys grows.
How does the program handle many dynamic keys efficiently?
Analyze the time complexity of the following code snippet.
interface Data {
[key: string]: number;
}
const data: Data = {};
function addEntry(key: string, value: number) {
data[key] = value;
}
function getEntry(key: string): number | undefined {
return data[key];
}
This code stores and retrieves numbers using dynamic string keys in an object.
- Primary operation: Accessing or setting a value by a dynamic key in an object.
- How many times: Each call accesses or sets one key directly without looping.
Each access or update looks up the key directly, so the time does not increase as more keys are added.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation time stays about the same no matter how many keys exist.
Time Complexity: O(1)
This means accessing or setting a value by a dynamic key takes the same short time regardless of how many keys are stored.
[X] Wrong: "Accessing a dynamic key gets slower as more keys are added because it searches through all keys."
[OK] Correct: Objects use a fast lookup method (like a hash table), so they find keys quickly without checking each one.
Understanding how dynamic keys work helps you explain how data structures handle many entries efficiently, a useful skill in many coding tasks.
"What if we used an array of key-value pairs instead of an object? How would the time complexity change?"
Practice
index signature in TypeScript when working with objects?Solution
Step 1: Understand index signatures
Index signatures let you define objects that can have any number of keys, but all keys must have values of the same type.Step 2: Compare options
To allow objects to have dynamic keys with values of a specific type correctly describes this purpose. Options B, C, and D describe other unrelated concepts.Final Answer:
To allow objects to have dynamic keys with values of a specific type -> Option DQuick Check:
Index signature = dynamic keys with uniform value type [OK]
- Thinking index signatures fix keys instead of allowing dynamic keys
- Confusing index signatures with tuple or array types
- Assuming index signatures restrict to one key-value pair
Solution
Step 1: Recall index signature syntax
The syntax is{ [key: KeyType]: ValueType }. For string keys and number values, it is{ [key: string]: number }.Step 2: Check options
{ [key: string]: number } matches the correct syntax. { [key: number]: string } reverses key and value types. Options B and D are object properties, not index signatures.Final Answer:
{ [key: string]: number } -> Option AQuick Check:
Index signature syntax = {[key: string]: number} [OK]
- Swapping key and value types in the signature
- Using object property syntax instead of index signature
- Using number keys when string keys are intended
console.log(userScores['alice'])?
interface Scores {
[username: string]: number;
}
const userScores: Scores = {
alice: 10,
bob: 15
};
console.log(userScores['alice']);Solution
Step 1: Understand the object and index signature
The interface allows any string key with number values. The object has keys 'alice' and 'bob' with values 10 and 15.Step 2: Access the value for key 'alice'
AccessinguserScores['alice']returns 10, the value assigned to 'alice'.Final Answer:
10 -> Option AQuick Check:
userScores['alice'] = 10 [OK]
- Confusing key with value and expecting 'alice' as output
- Assuming undefined for existing keys
- Mixing up values of different keys
interface Data {
[key: string]: number;
}
const data: Data = {
id: 1,
name: "John"
};Solution
Step 1: Check index signature type
The interface says all keys (strings) must have number values.Step 2: Check object values
The 'id' key has value 1 (number), which is correct. The 'name' key has value "John" (string), which violates the number value rule.Final Answer:
The value of 'name' is a string, but should be a number -> Option BQuick Check:
Value types must match index signature [OK]
- Thinking keys must be numbers instead of strings
- Ignoring value type mismatch errors
- Assuming index signatures allow mixed value types
Solution
Step 1: Understand the requirement
We need an object with number keys (user IDs) and values that are objects with string keys and boolean values.Step 2: Match interface to requirement
interface Preferences { [userId: number]: { [prefKey: string]: boolean } } uses an index signature for userId as number keys, and nested index signature for preference keys as strings with boolean values, matching the requirement exactly.Final Answer:
interface Preferences { [userId: number]: { [prefKey: string]: boolean } } -> Option CQuick Check:
Nested index signatures for dynamic keys [OK]
- Using string keys for userId instead of number
- Confusing property syntax with index signatures
- Not nesting index signatures for inner dynamic keys
Ready to prove it?
Pass the test and this pattern moves unknown
