Course contentsShow
← TypeScript
Lesson 311 of 1,7967. ObjectsFree lesson

Basic Index Signature Syntax

Writing your first index signature with [key: string]: ValueType to allow any string key with a specific value type.

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 word key is just a parameter name (you can use any name like prop or name).
  • : 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.