Sub topic 2
Declaring an Index Signature
This chapter shows how to write an index signature and what the compiler does with it. It assumes you know basic TypeScript types, interfaces and type aliases, and how to access JavaScript object properties with dot and bracket notation. It also assumes you are comfortable with union types and undefined. Later chapters cover key types, mixing in known properties, and safe lookups in detail. Here the goal is the core syntax and the rules that follow from it.
The problem an index signature solves
Some objects are used as dictionaries. Their keys are not known when you write the code, and they are added at runtime: word counts, user scores, lookup tables keyed by an ID. TypeScript's normal object types list each property by name, so they cannot describe this. An index signature describes the shape of the whole collection instead: "every property whose key is a string has a value of this type."
The syntax
An index signature sits inside an object type. It has a key label, a key type, and a value type:
const scores: { [name: string]: number } = {};
scores["alice"] = 90;
scores.bob = 85;
// scores.carol = "A"; // Error: Type 'string' is not assignable to type 'number'.Read [name: string]: number as "for any key name of type string, the value is a number." Three parts matter:
nameis only a label. It documents what the key means and has no effect on type checking. You could write[k: string]or[word: string]and get identical behavior.stringis the key type. It says which keys the signature covers. The next chapter covers the other allowed key types.numberis the value type. Every property reached through the signature must be assignable to it.
The compiler accepts both scores["alice"] and scores.bob. For a string index signature, dot access and bracket access are equivalent. If you want to force bracket access for dictionary keys, so they look different from real properties, enable the noPropertyAccessFromIndexSignature compiler option. With it on, scores.bob becomes an error and scores["bob"] is required.
Three places to write one
You can write an index signature inline, in an interface, or in a type alias. The compiler treats them the same way.
// Inline, as an annotation
let inline: { [key: string]: boolean } = {};
// In an interface
interface FeatureFlags {
[flag: string]: boolean;
}
// In a type alias
type Translations = {
[phrase: string]: string;
};
const flags: FeatureFlags = { darkMode: true, beta: false };
const french: Translations = { hello: "bonjour", goodbye: "au revoir" };
inline = { ...flags };When the same shape appears in several places, make it generic once and reuse it:
interface Dictionary<T> {
[key: string]: T;
}
type Inventory = Dictionary<number>;
type Users = Dictionary<{ name: string; admin: boolean }>;
const stock: Inventory = { apples: 12, pears: 4 };
const users: Users = {
u1: { name: "Ann", admin: true },
u2: { name: "Raj", admin: false },
};
console.log(stock.apples + users.u1.name.length);How the compiler uses the signature
The signature applies in three situations: when you create the object, when you write a property, and when you read one.
- Creating. Every property in an object literal assigned to the type must have a value of the right type. Any key name is allowed.
- Writing.
dict[key] = valueis checked against the value type. The key may be any expression of the key type, including a variable. - Reading.
dict[key]has the value type, whatever the key is.
The diagram shows how the compiler resolves a property access on a type that has both named properties and an index signature.
Without an index signature, the last branch is what you hit when you try to build a dictionary from a plain {}:
const counts = {};
// counts["a"] = 1; // Error: Element implicitly has an 'any' type because expression of type '"a"' can't be used to index type '{}'.The empty literal has the type {}, which has no properties and no index signature. Annotating the variable fixes it. Here is a complete function that builds a dictionary:
function countLetters(text: string): { [letter: string]: number } {
const counts: { [letter: string]: number } = {};
for (const ch of text) {
counts[ch] = (counts[ch] ?? 0) + 1;
}
return counts;
}
console.log(countLetters("banana")); // { b: 1, a: 3, n: 2 }The ?? 0 handles the first time a letter is seen. Reads from an index signature are typed as number, but at runtime a missing key gives undefined. That mismatch is the main hazard of index signatures, and the next sections come back to it.
The type is a claim, not a guarantee
An index signature tells the compiler that any key you look up has a value. It does not check that the key exists.
const scores: { [name: string]: number } = { alice: 90 };
const zed = scores["zed"]; // type: number
console.log(zed); // undefined at runtimeThe compiler infers number for zed, but the value is undefined. If you then call zed.toFixed(0), the code compiles and throws at runtime.
Typos are not caught
The flexibility that makes index signatures useful for dictionaries makes them a poor fit for objects with a fixed shape. Any key is legal, so a misspelled name compiles:
const scores: { [name: string]: number } = {};
scores.alice = 90;
scores.alcie = 91; // typo: compiles, creates a second keyIf you know the keys in advance, list them as named properties or use a union of literal keys with Record. Reserve index signatures for keys that are only known at runtime.
Interfaces and type aliases are not assignable in the same way
Assigning an existing object to a dictionary type shows a difference between type aliases and interfaces. TypeScript gives object literal type aliases an implicit index signature, as long as all their known properties match the value type. Interfaces do not get one, because an interface can be extended later by declaration merging, and a merged property could break the dictionary rule.
interface PointInterface {
x: number;
y: number;
}
type PointAlias = {
x: number;
y: number;
};
const fromInterface: PointInterface = { x: 1, y: 2 };
const fromAlias: PointAlias = { x: 1, y: 2 };
const ok: { [key: string]: number } = fromAlias;
// const bad: { [key: string]: number } = fromInterface;
// Error: Index signature for type 'string' is missing in type 'PointInterface'.
console.log(ok.x);If you hit this error when passing an interface-typed value to a function that takes a dictionary, you have three options. Change the interface to a type alias, add an explicit index signature to the interface, or change the function's parameter type to something more precise.
keyof on a dictionary
keyof on a type with a string index signature gives string | number. JavaScript converts numeric keys to strings, so TypeScript accepts both when you index.
type Scores = { [name: string]: number };
type ScoreKey = keyof Scores; // string | number
const s: Scores = { "1": 10 };
console.log(s[1]); // 10: the number 1 is converted to the key "1"This matters when you write generic helpers that take keyof T. A dictionary type will accept numeric arguments even though the keys are stored as strings.
Restrictions on the key type
The key type in an index signature cannot be a literal type, a union of literals, or a generic type parameter. This is rejected:
// interface Bad {
// [key: "low" | "high"]: number;
// // Error: An index signature parameter type cannot be a literal type or generic type.
// // Consider using a mapped object type instead.
// }The error message points to the right fix: a mapped type such as Record<"low" | "high", number>. The "Record and mapped types" chapter covers that. The allowed key types are string, number, symbol, and template literal patterns, and the "Which key types are allowed" chapter covers them.
One signature per key type
A type can have several index signatures, but only one for each key type. A string signature and a number signature can coexist if the number signature's value type is assignable to the string signature's value type. This is because a numeric lookup is also a string lookup in JavaScript.
interface Mixed {
[key: string]: string | number;
[index: number]: number;
}
const m: Mixed = { 0: 5, label: "five" };
console.log(m[0], m.label);Here number is assignable to string | number, so the declaration is valid. Reversing the two value types would be an error.
Summary of the rules
| Situation | Behavior | Column |
|---|---|---|
| Key label name | Documentation only; has no effect on checking | |
| Create or assign | Every value must be assignable to the value type | |
| Read `dict[key]` | Typed as the value type (or `T \ | undefined` with `noUncheckedIndexedAccess`) |
| Dot access `dict.key` | Allowed unless `noPropertyAccessFromIndexSignature` is on | |
| Misspelled key | Not an error; any key is valid | |
| Interface to dictionary | Not assignable unless the interface declares the signature itself | |
| `keyof` a string signature | `string \ | number` |
Exercise
The following code compiles without errors. Explain why the last line is a problem at runtime, and name the tsconfig.json option that would make the compiler report it.
const prices: { [item: string]: number } = { tea: 3 };
const coffee = prices["coffee"];
console.log(coffee.toFixed(2));
Show answer
The index signature types every lookup as number, so coffee is typed number even though the key "coffee" does not exist. At runtime coffee is undefined, and calling toFixed on it throws a TypeError. Enabling noUncheckedIndexedAccess makes the read number | undefined, so the compiler rejects coffee.toFixed(2) until you check for undefined.
Exercise
Write a generic Dictionary<T> interface with a string index signature. Then write a function groupByLength(words: string[]) that returns a Dictionary<string[]> mapping each word length (as a string key) to the words of that length.
Show answer
interface Dictionary<T> { [key: string]: T; } function groupByLength(words: string[]): Dictionary<string[]> { const groups: Dictionary<string[]> = {}; for (const word of words) { const key = String(word.length); const existing = groups[key]; if (existing) { existing.push(word); } else { groups[key] = [word]; } } return groups; } console.log(groupByLength(["a", "to", "be", "cat"])); // { "1": ["a"], "2": ["to", "be"], "3": ["cat"] }