Script Valley
TypeScript: Complete Course from Zero
Object Types and InterfacesLesson 2.4

Index signatures and dynamic object keys in TypeScript

index signature syntax, string index signatures, number index signatures, mixed known and dynamic keys, Record utility type

Index signatures

When an object's keys are dynamic but all values share a type, use an index signature:

interface StringMap {
  [key: string]: string;
}

const headers: StringMap = {
  "Content-Type": "application/json",
  "Authorization": "Bearer abc123"
};

headers["X-Custom"] = "value"; // valid
headers["count"] = 42;        // Error: number not assignable to string

Mixing fixed and dynamic keys

interface Config {
  version: number;
  [key: string]: string | number; // must include number because version is number
}

Record utility type

Record<K, V> is a cleaner shorthand for common index signature patterns:

const scores: Record = {
  alice: 95,
  bob: 88
};

// Restrict keys to a union
type Role = "admin" | "user" | "guest";
const permissions: Record = {
  admin: true,
  user: false,
  guest: false
};

Prefer Record for known key sets and index signatures for fully dynamic keys.

Up next

Intersection types in TypeScript combining multiple types

Sign in to track progress