0
0
Typescriptprogramming~5 mins

Index signatures for dynamic keys in Typescript

Choose your learning style9 modes available
Introduction
Index signatures let you describe objects with keys you don't know in advance. This helps when you want to store many similar items with different names.
You want to store user settings where each setting name can vary.
You need to keep track of scores for players with unknown player names.
You want to create a dictionary where keys are dynamic and values have the same type.
You are working with JSON data that has flexible keys.
You want to access object properties using variables instead of fixed names.
Syntax
Typescript
interface MyObject {
  [key: string]: ValueType;
}
The key type is usually 'string' or 'number'.
All properties must match the ValueType declared.
Examples
This means any string key will have a number value, like player scores.
Typescript
interface Scores {
  [playerName: string]: number;
}
Keys are setting names, values can be string or number.
Typescript
interface Settings {
  [settingName: string]: string | number;
}
Keys are numbers (user IDs), values are ages.
Typescript
const userAges: { [id: string]: number } = {
  101: 25,
  102: 30
};
Sample Program
This example creates a phone book where names are keys and phone numbers are values. It prints the numbers for Alice and Bob.
Typescript
interface PhoneBook {
  [name: string]: string;
}

const contacts: PhoneBook = {
  "Alice": "123-4567",
  "Bob": "987-6543"
};

console.log(contacts["Alice"]);
console.log(contacts["Bob"]);
OutputSuccess
Important Notes
Index signatures allow any number of properties with matching types.
You cannot mix incompatible types for values when using index signatures.
Using index signatures helps when keys are not fixed or known beforehand.
Summary
Index signatures describe objects with dynamic keys.
They ensure all keys have values of the same type.
Useful for flexible data like dictionaries or maps.