Sub topic 3
Which Key Types Are Allowed in Index Signatures
This chapter assumes you can write basic TypeScript interfaces and type aliases. It also assumes you know that JavaScript object keys are strings or symbols, and that you can read a union type such as string | undefined.
The previous chapter introduced the syntax [key: string]: T. The name in the brackets is only a label for readers and error messages. The type after the colon is the one that matters, and TypeScript accepts only a short list of types there. This chapter covers that list, how the key types interact, and the runtime behavior that explains why the rules exist.
The allowed key types
An index signature parameter can be one of these:
| Key type | Example | Since | Column |
|---|---|---|---|
| `string` | `[key: string]: T` | Always | |
| `number` | `[index: number]: T` | Always | |
| `symbol` | `[key: symbol]: T` | TypeScript 4.4 | |
| Template literal pattern | `` [key: `data-${string}`]: T `` | TypeScript 4.4 | |
| Union of the above | `[key: string \ | number]: T` | TypeScript 4.4 |
Other types are rejected. These include string literal types such as "a", unions of literals such as "a" | "b", boolean, object types, and generic type parameters. The compiler reports error TS1337, which says that an index signature parameter type cannot be a literal type or generic type, and suggests a mapped type instead.
String index signatures
A string index signature is the most common form. It accepts any string key:
const prices: { [item: string]: number } = {};
prices["apple"] = 1.2;
prices.pear = 0.9;JavaScript converts every non-symbol property key to a string before the lookup happens. TypeScript reflects this by allowing numbers wherever a string index signature applies:
const dict: { [key: string]: string } = {};
dict[1] = "one";
console.log(dict["1"]); // "one"
console.log(Object.keys(dict)); // ["1"]The number 1 and the string "1" address the same property, so one string signature covers both.
Number index signatures
A number index signature describes values stored under numeric keys. Arrays are the standard example. The type string[] behaves as if it declared [index: number]: string.
const roles: { [id: number]: string } = {};
roles[1] = "admin";
roles[2] = "editor";
console.log(roles[1]); // "admin"A number signature does not create a real numeric key at runtime. Property keys are always strings, so roles[1] reads the property named "1". The number signature only tells TypeScript that numeric-looking access is legal and what type it returns.
Two details follow from this conversion:
- Keys such as
1.5and-1are legal number keys and become the strings"1.5"and"-1". - Integer-like keys are ordered differently from other keys when you enumerate an object.
The second point surprises many people. Object.keys lists integer-like keys first, in ascending numeric order, then other string keys in insertion order:
const o: Record<string, string> = {};
o["b"] = "B";
o["2"] = "two";
o["1"] = "one";
o["a"] = "A";
console.log(Object.keys(o)); // ["1", "2", "b", "a"]If insertion order matters for your data, objects with numeric-looking keys are a poor fit. The Map section later in this tutorial covers that case.
Using string and number signatures together
An object type can declare both signatures. TypeScript then requires the number signature's value type to be assignable to the string signature's value type. This is the same rule that governs named properties, and it exists because every numeric lookup is also a string lookup.
interface Mixed {
[key: string]: string | number;
[index: number]: number;
}
const m: Mixed = { 0: 10, label: "ten" };
const first: number = m[0];
const label: string | number = m["label"];The reverse declaration fails:
interface Broken {
[key: string]: string;
// [index: number]: number;
// Error: 'number' index type 'number' is not assignable to 'string' index type 'string'.
}The commented line is invalid because m[0] would read the same property as m["0"], and the string signature promises that value is a string. The number signature cannot promise a number for the same property.
Symbol index signatures
Since TypeScript 4.4 you can index by symbol. This fits objects that use symbols as keys, for example to attach metadata that must not collide with ordinary string keys.
const idKey = Symbol("id");
const otherKey = Symbol("other");
const tags: { [key: symbol]: string } = {};
tags[idKey] = "user-1";
tags[otherKey] = "user-2";
console.log(tags[idKey]); // "user-1"
console.log(Object.keys(tags)); // []
console.log(Object.getOwnPropertySymbols(tags).length); // 2Object.keys, Object.entries, for...in and JSON.stringify all skip symbol keys. A symbol-keyed dictionary is invisible to most code that walks objects. To enumerate such keys, use Object.getOwnPropertySymbols or Reflect.ownKeys.
Unions of key types
You can combine key types in one signature. It is shorthand for declaring each signature separately with the same value type:
type AnyKeyed = { [key: string | number | symbol]: boolean };
const flags: AnyKeyed = {};
flags["debug"] = true;
flags[42] = false;
flags[Symbol.iterator] = true;Here PropertyKey is the built-in alias for string | number | symbol, so { [key: PropertyKey]: boolean } is equivalent. You will rarely need all three. A union is mainly useful when you write generic helpers that must accept any legal key.
A type alias that resolves to an allowed type is also fine, because TypeScript checks the resolved type:
type UserId = string;
const users: { [id: UserId]: { name: string } } = {};
users["u1"] = { name: "Ana" };Note that this does not create a distinct "branded" ID type. UserId is just another name for string, so any string is accepted.
Template literal pattern keys
Since TypeScript 4.4, a signature key can be a template literal pattern such as ` data-${string} `. Only keys that match the pattern are constrained, and other keys are free. A later chapter covers these in detail. The point here is that a pattern counts as an allowed key type:
interface Slots {
[key: `slot-${number}`]: string;
}
const slots: Slots = {
"slot-1": "header",
"slot-2": "footer",
};Key types that are not allowed
The most common mistake is trying to restrict the keys to a fixed set of names with an index signature. TypeScript rejects it:
type Level = "low" | "high";
// interface Bad {
// [key: Level]: number;
// // Error TS1337: An index signature parameter type cannot be a literal type
// // or generic type. Consider using a mapped object type instead.
// }
type Good = { [K in Level]: number };
const limits: Good = { low: 1, high: 10 };A mapped type produces one real property per name, so the result requires both low and high. An index signature describes an open set of keys with a shared value type. The two are different tools, and Record<Level, number> is the usual shorthand for the mapped form.
Other rejected parameter types, and the alternatives, are:
booleanorobject: convert the key to a string yourself, or use aMap<object, T>when you need object identity as the key.- A generic
K extends string: use a mapped type such as{ [P in K]: T }orRecord<K, T>. anyorunknown: usestring,numberorsymbolas appropriate.
Also remember that an index signature admits only one parameter. Writing [a: string, b: string]: T is a syntax error. If you need composite keys, join them into one string or use a template literal pattern.
Compatibility with a type's other properties
Declaring a key type also decides what the rest of the type must look like. A string signature requires every named property to match its value type, and a number signature applies the same rule only to properties whose names are numeric. The next chapter covers this rule in full. This example shows the number case:
interface Matrix {
[row: number]: number[];
name: string; // fine: "name" is not a numeric key
}
const m: Matrix = { 0: [1, 0], 1: [0, 1], name: "identity" };If the signature were [key: string]: number[], the name: string property would be an error.
Common errors
- Expecting number keys to exist at runtime.
{ [id: number]: T }still stores string keys.Object.keysreturns strings, soObject.keys(roles).map(k => roles[k])fails to type-check against a number-only signature. Convert withNumber(k)or use a string signature. - Declaring a number signature with an incompatible string signature. The number value type must be assignable to the string value type.
- Using a literal union as a key type. Use a mapped type or
Record. - Assuming
for...inorObject.keysshows symbol keys. They do not. - Relying on key order. Integer-like keys come first and sorted, regardless of when they were added.
Summary of the rules
- Allowed parameter types are
string,number,symbol, template literal patterns, and unions of these. - Literal types, unions of literals, and generic parameters are rejected. Use a mapped type.
- Number keys become strings at runtime, so a number signature's value type must be assignable to a string signature's value type.
- Symbol keys are hidden from the usual enumeration functions.
- Integer-like keys are enumerated first in ascending order.
Exercise
This interface fails to compile. Explain why, and show two different valid fixes. interface Inventory { [sku: string]: string; [slot: number]: number; }
Show answer
Reading inventory[0] reads the same runtime property as inventory["0"], so the string signature says that value is a string while the number signature says it is a number. The number signature's value type (number) must be assignable to the string signature's value type (string), and it is not. Fix 1: widen the string signature so it includes the number type, as in "[sku: string]: string | number;". Fix 2: make both signatures use the same value type, as in "[sku: string]: number; [slot: number]: number;". Removing the number signature also works if you never need numeric-specific typing.
Exercise
You want a type whose keys must be exactly "dev", "staging" and "prod", each mapped to a URL string. A colleague writes "[env: 'dev' | 'staging' | 'prod']: string" in an interface and gets error TS1337. Rewrite it correctly in one line, and say what the new type requires that the index signature version would not have.
Show answer
Write "type Endpoints = Record<'dev' | 'staging' | 'prod', string>;" or the equivalent mapped type "{ [E in 'dev' | 'staging' | 'prod']: string }". Unlike an index signature, which describes an open set of keys, this type has three real properties, so every object of this type must provide all three keys and no others.