Sub topic 3
Which Key Types Are Allowed in TypeScript Index Signatures
Assume you know basic TypeScript interfaces, type aliases, union types, and JavaScript property access. This chapter focuses on the key types that an index signature can describe.
An index signature types properties whose names are not known when you write the type. Its key type can be string, number, or symbol. It can also use a template literal pattern such as ` data-${string} `.
String keys
A string index signature allows any string property name:
interface Scores {
[name: string]: number;
}
const scores: Scores = {
alice: 90,
bob: 85,
};
scores["carol"] = 88;
scores.dan = 91;
console.log(scores["alice"]);Both bracket notation and dot notation access string-named properties. Dot notation works only when the property name is a valid identifier. Use brackets when the key comes from a variable or contains characters such as -.
const name = "alice";
console.log(scores[name]);
const field = "final-score";
const results: { [key: string]: number } = {};
results[field] = 100;A string index signature is useful for lookup tables, settings keyed by names, and dynamically created object properties.
Number keys
A number index signature describes numeric indexes:
interface MonthlyTotals {
[month: number]: number;
}
const totals: MonthlyTotals = {};
totals[1] = 1200;
totals[2] = 1350;
console.log(totals[1]);Number index signatures are common for arrays, tuples, and objects addressed by numeric positions. At runtime, JavaScript objects store ordinary property names as strings, so totals[1] and totals["1"] refer to the same property:
totals["1"] = 1400;
console.log(totals[1]); // 1400TypeScript still treats the declared access differently. A number index signature promises behavior for numeric keys. It does not generally mean that every arbitrary string is valid.
The keyof result also reflects the declared index type:
type NumericKeys = keyof MonthlyTotals; // numberFor a type with a string index signature, keyof includes both string and number, because JavaScript numeric property access can reach string-named properties:
type StringKeys = keyof { [key: string]: boolean }; // string | numberSymbol keys
A symbol is a unique JavaScript property key. Symbols do not collide with string keys, even when they have the same description.
interface Metadata {
[key: symbol]: string;
}
const metadata: Metadata = {};
const source = Symbol("source");
const version = Symbol("version");
metadata[source] = "import";
metadata[version] = "1";
console.log(metadata[source]);A symbol index signature accepts symbol keys, not strings or numbers:
type SymbolKeys = keyof Metadata; // symbolSymbols are useful when a property should be difficult to discover through normal string-based enumeration, or when independently developed code needs a collision-resistant key.
Combining string and number signatures
You can declare both string and number index signatures, but the number value type must be assignable to the string value type. This rule models JavaScript's conversion of numeric property names to strings.
interface Catalog {
[key: string]: string | number;
[index: number]: string;
}
const catalog: Catalog = {
0: "first",
title: "Products",
count: 3,
};
catalog[1] = "second";
catalog["category"] = "books";Here, every numeric value is a string, which is also allowed by the string signature's string | number value type.
| Key type | Example access | Typical use |
|---|---|---|
| `string` | `table["alice"]` | Named lookups |
| `number` | `items[0]` | Positions or numeric indexes |
| `symbol` | `metadata[token]` | Unique, collision-resistant keys |
| `` `data-${string}` `` | `attrs["data-id"]` | Restricted key patterns |
Template literal patterns
A template literal pattern restricts string keys to a specific form:
interface DataAttributes {
[key: `data-${string}`]: string;
}
const attributes: DataAttributes = {
"data-id": "42",
"data-role": "admin",
};
// attributes["aria-label"] = "User"; // ErrorThis is more precise than [key: string] when only a family of property names is valid.
Exercise
Which index signature should you use for an object whose keys must start with "env-" and whose values are strings?
Show answer
Use [key: env-${string}]: string.