Bird
Raised Fist0
Typescriptprogramming~10 mins

Index signatures for dynamic keys in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Index signatures for dynamic keys
Start: Define object type with index signature
↓
Use dynamic key to access or assign value
↓
Check if key type matches index signature
↓
Allow access/assign
↓
Retrieve or update value
↓
End
This flow shows how TypeScript uses index signatures to allow dynamic keys in objects, checking key types and allowing access or assignment if types match.
Execution Sample
Typescript
interface Scores {
  [player: string]: number;
}
const gameScores: Scores = {};
gameScores['Alice'] = 10;
const aliceScore = gameScores['Alice'];
Defines an object type with string keys and number values, assigns a score dynamically, then retrieves it.
Execution Table
StepActionKeyValueType CheckResult
1Define interface with index signature--N/AType allows string keys with number values
2Create empty object gameScores--N/AgameScores is {}
3Assign value 10 to key 'Alice'Alice10string key, number valueAssignment allowed
4Retrieve value for key 'Alice'Alice-string keyReturns 10
5Attempt assign string value to key 'Bob'Bob"high"string key, string valueError: Type mismatch
6Attempt access with number key 55-number keyError: Key type mismatch
💡 Execution stops after type errors on steps 5 and 6 prevent invalid assignments or access.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
gameScoresundefined{}{ 'Alice': 10 }{ 'Alice': 10 }{ 'Alice': 10 }
aliceScoreundefinedundefinedundefined1010
Key Moments - 2 Insights
Why does assigning a string value to a key cause an error?
Because the index signature requires values to be numbers, assigning a string violates the type, as shown in execution_table step 5.
Can we use a number as a key with this index signature?
No, the index signature specifies string keys only, so using a number key causes a type error, as in step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of gameScores after step 3?
A{ 'Alice': 10 }
B{}
C{ 'Alice': '10' }
Dundefined
💡 Hint
Check the 'Value' and 'Result' columns in row for step 3.
At which step does a type error occur due to value type mismatch?
AStep 4
BStep 5
CStep 3
DStep 2
💡 Hint
Look for 'Error: Type mismatch' in the 'Result' column.
If we change the index signature to [player: string]: string, what happens at step 3?
AAssignment allowed with number value
BAssignment allowed with string value
CError: Type mismatch
DNo change
💡 Hint
Refer to the type check logic in execution_table step 3 and how value types must match.
Concept Snapshot
Index signatures allow objects to have dynamic keys of a specified type.
Syntax: {[key: KeyType]: ValueType}
Keys must match KeyType, values must match ValueType.
Access and assignment check these types.
Type errors occur if types mismatch.
Full Transcript
This visual execution trace shows how TypeScript index signatures work for dynamic keys. We start by defining an interface with a string key and number value. Then we create an empty object of that type. Assigning a number value to a string key is allowed and stored. Retrieving the value by key returns the stored number. Assigning a string value to a key causes a type error because it violates the value type. Using a number as a key also causes a type error because the key type must be string. The variable tracker shows how the object and retrieved value change step by step. Key moments clarify why type mismatches cause errors. The quiz tests understanding of these steps and type rules.

Practice

(1/5)
1. What is the main purpose of an index signature in TypeScript when working with objects?
easy
A. To create arrays with fixed length
B. To define fixed keys with different types for each key
C. To restrict objects to only one key-value pair
D. To allow objects to have dynamic keys with values of a specific type

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    To allow objects to have dynamic keys with values of a specific type -> Option D
  4. Quick Check:

    Index signature = dynamic keys with uniform value type [OK]
Hint: Index signatures mean dynamic keys with same value type [OK]
Common Mistakes:
  • 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
2. Which of the following is the correct syntax for an index signature allowing string keys and number values in TypeScript?
easy
A. { [key: string]: number }
B. { key: string; value: number }
C. { [key: number]: string }
D. { key: number; value: string }

Solution

  1. Step 1: Recall index signature syntax

    The syntax is { [key: KeyType]: ValueType }. For string keys and number values, it is { [key: string]: number }.
  2. 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.
  3. Final Answer:

    { [key: string]: number } -> Option A
  4. Quick Check:

    Index signature syntax = {[key: string]: number} [OK]
Hint: Index signature syntax: {[key: KeyType]: ValueType} [OK]
Common Mistakes:
  • Swapping key and value types in the signature
  • Using object property syntax instead of index signature
  • Using number keys when string keys are intended
3. Given the following TypeScript code, what will be the output of console.log(userScores['alice'])?
interface Scores {
  [username: string]: number;
}
const userScores: Scores = {
  alice: 10,
  bob: 15
};
console.log(userScores['alice']);
medium
A. 10
B. alice
C. undefined
D. 15

Solution

  1. 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.
  2. Step 2: Access the value for key 'alice'

    Accessing userScores['alice'] returns 10, the value assigned to 'alice'.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    userScores['alice'] = 10 [OK]
Hint: Access dynamic key value directly with bracket notation [OK]
Common Mistakes:
  • Confusing key with value and expecting 'alice' as output
  • Assuming undefined for existing keys
  • Mixing up values of different keys
4. Identify the error in the following TypeScript code using an index signature:
interface Data {
  [key: string]: number;
}
const data: Data = {
  id: 1,
  name: "John"
};
medium
A. The interface should use [key: number] instead
B. The value of 'name' is a string, but should be a number
C. Index signatures cannot use string keys
D. The key 'id' should be a number, not a string

Solution

  1. Step 1: Check index signature type

    The interface says all keys (strings) must have number values.
  2. 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.
  3. Final Answer:

    The value of 'name' is a string, but should be a number -> Option B
  4. Quick Check:

    Value types must match index signature [OK]
Hint: All values must match index signature type [OK]
Common Mistakes:
  • Thinking keys must be numbers instead of strings
  • Ignoring value type mismatch errors
  • Assuming index signatures allow mixed value types
5. You want to create a TypeScript object to store user preferences where keys are user IDs (numbers) and values are objects with dynamic string keys and boolean values. Which of the following interface definitions correctly models this?
hard
A. interface Preferences { [userId: string]: { [prefKey: number]: boolean } }
B. interface Preferences { userId: number; prefKey: string; value: boolean }
C. interface Preferences { [userId: number]: { [prefKey: string]: boolean } }
D. interface Preferences { [userId: number]: { prefKey: string; value: boolean } }

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    interface Preferences { [userId: number]: { [prefKey: string]: boolean } } -> Option C
  4. Quick Check:

    Nested index signatures for dynamic keys [OK]
Hint: Use nested index signatures for nested dynamic keys [OK]
Common Mistakes:
  • Using string keys for userId instead of number
  • Confusing property syntax with index signatures
  • Not nesting index signatures for inner dynamic keys
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard