Sub topic 6
Index Signatures for Dictionary-Like Objects
This chapter assumes you can write interfaces and type aliases with optional and readonly properties, and that you know how keyof and basic object types work. It covers index signatures, which describe objects whose property names are not known ahead of time.
The problem: keys you cannot list
An interface normally names every property it allows. That works for a User, but not for a lookup table such as word counts, HTTP headers, or translations. The keys come from data, so you cannot write them in the declaration.
An index signature describes the type of every property whose key matches a key type. It has this form:
interface WordCounts {
[word: string]: number;
}
const counts: WordCounts = {};
counts["hello"] = 2;
counts.world = 5;
console.log(counts["hello"] + counts.world); // 7The name inside the brackets (word) is only a label for readers. It has no effect on type checking. The part after the colon is the key type, and the part after the closing bracket is the value type. Here, any string key must hold a number.
The same idea works in a type alias:
type Translations = {
[key: string]: string;
};
const en: Translations = { hello: "Hello", bye: "Goodbye" };Both forms are equivalent. Because a type alias can also use a mapped type, there is a third spelling, Record<string, number>, covered later in this chapter.
Allowed key types
An index signature key must be string, number, symbol, a template literal pattern, or a union of these. Literal unions such as "a" | "b" are not allowed in an index signature. A mapped type handles that case instead.
| Key type | Matches | Example |
|---|---|---|
| `string` | Any string key, and numeric keys too | `[k: string]: T` |
| `number` | Numeric keys only | `[i: number]: T` |
| `symbol` | Symbol keys | `[s: symbol]: T` |
| Template literal | Strings matching the pattern | `[k: \`data-${string}\`]: T` |
A template literal key narrows which strings the signature applies to:
interface DataAttributes {
[name: `data-${string}`]: string;
}
const attrs: DataAttributes = {
"data-id": "42",
"data-role": "admin",
};
// const bad: DataAttributes = { id: "42" }; // error: 'id' does not match the patternHow the string and number keys relate
JavaScript converts every property key to a string, except symbols. So obj[1] and obj["1"] read the same property. TypeScript reflects this: a string index signature also accepts numeric access.
interface Names {
[id: string]: string;
}
const names: Names = { "1": "Ada", "2": "Grace" };
console.log(names[1]); // "Ada", number access is allowed on a string indexWhen you declare both a number and a string signature, the number signature's value type must be assignable to the string signature's value type. This rule exists because a numeric access also reaches the string signature.
interface Mixed {
[key: string]: string | number;
[index: number]: number; // OK: number is assignable to string | number
}If you reverse the types, so that the number signature returns string while the string signature returns number, the compiler reports an error.
Mixing known properties with an index signature
You can declare named properties next to an index signature. Every named property must then be assignable to the index signature's value type, because the signature claims that all matching keys hold that type.
interface Scores {
total: number;
[player: string]: number;
}
// interface Broken {
// label: string; // error: 'string' is not assignable to 'number'
// [player: string]: number;
// }When the named properties have different types, widen the value type to a union:
interface Settings {
name: string;
retries: number;
[extra: string]: string | number;
}
const s: Settings = { name: "api", retries: 3, timeout: 30 };The cost is that reading an unknown key gives you the whole union. You must narrow it before use:
function show(s: Settings, key: string): string {
const v = s[key];
return typeof v === "number" ? v.toFixed(0) : v;
}Named properties keep their precise types. s.name is string, not string | number.
Index access can lie: missing keys
An index signature promises a value for every key. At runtime, a missing key returns undefined, but the type says number.
const counts: Record<string, number> = { a: 1 };
const n = counts["missing"]; // type: number, runtime value: undefined
console.log(n.toFixed(2)); // compiles, throws TypeError at runtimeThere are two ways to make this honest.
- Turn on the
noUncheckedIndexedAccesscompiler option intsconfig.json. Index reads then have typeT | undefined, which forces a check. - Put
undefinedin the value type yourself, for example[key: string]: number | undefined.
function increment(counts: Record<string, number>, word: string): void {
counts[word] = (counts[word] ?? 0) + 1;
}With noUncheckedIndexedAccess enabled, the ?? is required for the code to compile in strict style. Without it, the code compiles but hides the bug if you forget the default. This option also affects array element access, so enabling it in an existing project can produce many new errors. Plan for a cleanup pass.
Readonly index signatures
Add readonly to prevent writes through the signature:
interface Lookup {
readonly [key: string]: string;
}
const lookup: Lookup = { a: "x" };
console.log(lookup["a"]);
// lookup["a"] = "y"; // error: Index signature in type 'Lookup' only permits reading.This is a compile-time restriction only. It does not freeze the object at runtime.
Index signatures and excess property checks
A fresh object literal assigned to a type with named properties and no index signature is checked for extra properties. An index signature disables that check for matching keys, since every key is allowed.
interface Strict {
id: number;
}
interface Loose {
id: number;
[key: string]: unknown;
}
// const a: Strict = { id: 1, extra: true }; // error: excess property
const b: Loose = { id: 1, extra: true }; // OKUsing unknown as the value type is a common way to say "other properties are allowed, but I make no claims about them". It keeps callers from using those values without narrowing. Using any would remove that safety.
Interfaces versus type aliases for implicit index signatures
Interfaces and type aliases behave differently when you assign a value to an index-signature type. An object type written as a type alias (or an object literal's inferred type) gets an implicit index signature. An interface does not.
type PointAlias = { x: number; y: number };
interface PointInterface {
x: number;
y: number;
}
function sum(values: Record<string, number>): number {
return Object.values(values).reduce((a, b) => a + b, 0);
}
const a: PointAlias = { x: 1, y: 2 };
const b: PointInterface = { x: 1, y: 2 };
sum(a); // OK
// sum(b); // error: Index signature for type 'string' is missing in type 'PointInterface'The reason is that an interface can be extended or merged elsewhere with properties of other types. TypeScript cannot be sure that an interface only holds numbers, so it refuses the assignment. A type alias is closed, so the compiler can check all its properties. This difference is one of the few practical cases where the choice between the two constructs changes whether code compiles. If a function accepts Record<string, T> and callers hold interface-typed values, change the parameter type or declare the caller's type as an alias.
Record, Map, and when to use an index signature
Record<string, number> is a built-in alias that expands to a mapped type, { [x: string]: number }. It behaves like an index signature when the key is string. For a literal union key it produces required named properties instead:
type Level = "low" | "high";
type Limits = Record<Level, number>; // { low: number; high: number }
const limits: Limits = { low: 1, high: 10 };For a dictionary whose keys change at runtime, you have another option: the Map class. Compare the two:
| Concern | Index signature or `Record` | `Map<K, V>` |
|---|---|---|
| Key types | string, number, symbol | Any value, including objects |
| Inherited keys | Prototype keys such as `toString` can appear | No inherited keys |
| Iteration order | Integer-like keys first, then insertion order | Insertion order |
| Size | Count with `Object.keys(o).length` | `map.size` |
| JSON | Serializes directly | Needs conversion |
An object used as a dictionary inherits properties from Object.prototype. A lookup of "constructor" on an empty object returns a function, not undefined, which can break word-count code. For untrusted keys, use a Map, or create the object with Object.create(null). Use an index signature when the data is plain JSON-like data or the keys are fixed by a protocol.
Common mistakes
- Declaring a named property whose type is not assignable to the index signature's value type.
- Trusting index reads on dictionaries without
noUncheckedIndexedAccess. - Using
{ [key: string]: any }and losing all checking. Preferunknown, or a union of the real value types. - Expecting a literal union key to work in an index signature. Use
Recordor a mapped type. - Passing an interface-typed value to a parameter typed
Record<string, T>and being surprised by the missing index signature error.
Exercise
This code fails to compile. Why, and how do you fix it so that title stays a string and other properties can be numbers?
interface Item {
title: string;
[key: string]: number;
}
Show answer
The named property title is a string, but the index signature requires every property to be a number, so title is not assignable to the signature's value type. Widen the value type to a union: [key: string]: string | number;. title keeps its exact type string, and other keys are typed string | number.
Exercise
Given const counts: Record<string, number> = {};, what is the compile-time type of counts["x"], what is its runtime value, and which tsconfig option makes the compile-time type match the runtime value?
Show answer
The compile-time type is number, the runtime value is undefined, and enabling noUncheckedIndexedAccess makes the type number | undefined, so you must handle the missing case.
Exercise
Why does sum(b) fail when b is declared with an interface and passes when b is declared with a type alias of the same shape, assuming sum takes Record<string, number>?
Show answer
A type alias for an object type gets an implicit index signature, because its set of properties is closed. An interface can be extended or merged elsewhere with properties of other types, so TypeScript does not give it an implicit index signature and reports that the index signature is missing.