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

String vs Number Index Signatures

Comparing [key: string] and [key: number] index signatures and understanding when each is appropriate for your data.

String vs Number Index Signatures

You'll learn: When to use [key: string] versus [key: number] index signatures, and how they differ in what data they allow.

The Core Difference

In TypeScript, you can define index signatures using either string or number keys, and choosing the right one depends on how you'll access your data.

A string index signature ([key: string]: Type) allows any string key—perfect for objects where you'll use property names like user.firstName or settings["theme"].

A number index signature ([key: number]: Type) is designed for array-like structures where you access values by numeric index, like items[0] or scores[42].

String Index Signatures

interface UserScores {
  [username: string]: number;
}

const scores: UserScores = {
  alice: 95,
  bob: 87,
  charlie: 92
};

console.log(scores["alice"]); // 95

Use when: You have object properties with unpredictable string keys (like usernames, IDs, or dynamic configuration keys).

Number Index Signatures

interface GameBoard {
  [position: number]: string;
}

const board: GameBoard = {
  0: "X",
  1: "O",
  2: "X"
};

console.log(board[1]); // "O"

Use when: You're creating array-like structures where numeric indexing makes sense.

The Key Rule

Important: In JavaScript, all object keys become strings under the hood. TypeScript reflects this reality—if you use a number index signature, you can still access those properties with string versions of the numbers, but TypeScript enforces numeric-looking access patterns at the type level.

Key Takeaway: Use [key: string] for general object properties with string keys; use [key: number] for array-like data accessed by numeric index. Choose based on how your data will naturally be accessed.