Basic Index Signature Syntax
What you'll learn: How to write an index signature that allows any string key to map to a specific value type in an object.
The Problem Recap
You've seen that index signatures solve the problem of typing objects with unpredictable property names. Now let's learn the exact syntax to write them.
The Syntax Pattern
An index signature follows this structure:
{
[key: string]: ValueType
}
Let me break down each part:
[key: string]- This declares that any string can be used as a property name. The wordkeyis just a parameter name (you can use any name likeproporname).: ValueType- This specifies what type all those properties must have.
Basic Examples
Here's a simple dictionary of scores:
const scores: { [name: string]: number } = {
alice: 95,
bob: 87,
charlie: 92
};
scores.diana = 88; // ✓ Valid
scores.evan = "A+"; // ✗ Error: Type 'string' is not assignable to type 'number'
And a settings object with boolean flags:
const flags: { [setting: string]: boolean } = {
darkMode: true,
notifications: false
};
Think of It Like a Pattern
The index signature is like saying: "This object is a container where any string key is allowed, but every value must be the same type." It's a pattern match for the entire object's structure.
Key Takeaway: Index signatures use [key: string]: ValueType syntax to allow any string property name while enforcing a consistent value type across all properties.