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.
interface MyObject {
[key: string]: ValueType;
}interface Scores {
[playerName: string]: number;
}interface Settings {
[settingName: string]: string | number;
}const userAges: { [id: string]: number } = { 101: 25, 102: 30 };
interface PhoneBook {
[name: string]: string;
}
const contacts: PhoneBook = {
"Alice": "123-4567",
"Bob": "987-6543"
};
console.log(contacts["Alice"]);
console.log(contacts["Bob"]);index signature in TypeScript when working with objects?{ [key: KeyType]: ValueType }. For string keys and number values, it is { [key: string]: number }.console.log(userScores['alice'])?
interface Scores {
[username: string]: number;
}
const userScores: Scores = {
alice: 10,
bob: 15
};
console.log(userScores['alice']);userScores['alice'] returns 10, the value assigned to 'alice'.interface Data {
[key: string]: number;
}
const data: Data = {
id: 1,
name: "John"
};Pass the test and this pattern moves unknown