← Back to TypeScript Course | Chapter 4: Interfaces | Lesson 7 of 7

Index Signatures

An index signature allows an interface to describe objects whose property names are not known in advance. It specifies the type of keys and values those keys can contain.

Basic Index Signatures

An index signature, written with square brackets like [key: string]: number, defines the type of property names and values for an object whose exact keys aren't known ahead of time. This lets TypeScript type an object even when its properties are added dynamically.

Example: Basic Index Signatures

typescript
interface Scores {
  [key: string]: number;
}
const scores: Scores = { math: 90, science: 85 };
console.log(scores);

String Index Signatures

String index signatures are especially useful for dictionary-like objects and lookup tables, such as mapping country codes to country names. Every property accessed on that object, whatever its name, is guaranteed to be of the declared value type.

Example: String Index Signatures

typescript
interface CountryCodes {
  [code: string]: string;
}
const codes: CountryCodes = { IN: "India", US: "United States" };
console.log(codes["IN"]);

Number Index Signatures

A number index signature allows an object to be accessed using numeric keys, similar to how arrays work under the hood. This is less common than string index signatures but shows up when modeling array-like or sparse numeric collections.

Example: Number Index Signatures

typescript
interface StringArray {
  [index: number]: string;
}
const items: StringArray = { 0: "first", 1: "second" };
console.log(items[0]);

Index Signatures with Named Properties

An interface can combine an index signature with specific named properties, as long as those named properties are compatible with the type the index signature declares for their values. This lets you guarantee a few known properties exist while still allowing arbitrary additional ones.

Example: Index Signatures with Named Properties

typescript
interface Config {
  name: string;
  [key: string]: string;
}
const config: Config = { name: "App", version: "1.0" };
console.log(config);

Practical Dictionary Example

Index signatures are the standard way to type a dictionary object where keys get added dynamically at runtime, like a cache keyed by generated IDs. Without one, TypeScript would reject any property access using a key it can't verify at compile time.

Example: Practical Dictionary Example

typescript
interface Cache {
  [id: string]: number;
}
const cache: Cache = {};
cache["user_1"] = 100;
cache["user_2"] = 200;
console.log(cache);
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.