Skip to content
jshacks.dev
TypeScript

Index Signatures and Record Types

Learn how index signatures and Record types describe objects with unknown keys, where they conflict with named properties, and when a Map is the safer choice.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite, JavaScript and npm logos.

Some objects have keys you know when you write the code, and some have keys that only exist at runtime. A user profile has a name and an email. A word counter, a cache keyed by id or a map of HTTP headers has as many keys as the data supplies. TypeScript describes the second kind with an index signature, and it offers Record as a shorter way to say the same thing. This post covers index signatures and Record types side by side: the syntax, the one rule that stops them from mixing with named properties, the compiler flag that makes them honest, and the cases where a Map is the better tool. It targets TypeScript 6.x, and the reference material is in the handbook pages on object types and the Record utility type.

What an index signature says

An index signature declares the type of every value reached through a key of a given type. The syntax puts a parameter name and a key type in square brackets, then a value type after the colon.

index.tsTypeScript
const stock: { [item: string]: number } = { apples: 3, pears: 0 };

console.log(stock.apples);
console.log(stock["plums"]);
Text
3
undefined

The compiler accepts both reads. stock.apples exists, and stock["plums"] does not, yet the type says number for both. That second line is the first thing to understand about index signatures: they describe what a present key holds, and they say nothing about which keys are present. The runtime answer for a missing key is undefined, and the static type disagrees with it. We come back to that gap in the section on noUncheckedIndexedAccess.

The name inside the brackets, item here, is only documentation. It shows up in hover text and error messages and has no effect on checking. The key type may be string, number, symbol, a template literal pattern, or a union of those. Numeric index signatures are rarely worth declaring by hand, because arrays and tuples already carry one.

Record is the same idea in one line

Record<Keys, Value> is a utility type that builds an object type whose keys are Keys and whose values are Value. With string as the key type, it is equivalent to the index signature above.

record.tsTypeScript
const a: Record<string, number> = { apples: 3 };
const b: { [key: string]: number } = a;

type Level = "low" | "high";
const limits: Record<"low" | "high", number> = { low: 1 };
Text
record.ts(5,7): error TS2741: Property 'high' is missing in type '{ low: number; }' but required in type 'Record<"low" | "high", number>'.

The first two lines pass: the two spellings are interchangeable. The last declaration shows the second use of Record, which is not an index signature at all. When the key type is a union of literals, Record produces an object type with one required property per member. Leave one out and the compiler tells you which. That makes Record over a union a good way to force a lookup table to stay complete, because adding a new member to the union breaks every table that has not been updated.

So Record<string, T> means any number of keys, possibly none, and Record<"low" | "high", T> means exactly these keys. The first is for data, and the second is for configuration the code knows about.

The rule that named properties must follow

An interface can combine an index signature with named properties, but every named property must be assignable to the index signature's value type. The index signature is a promise about all keys, including the ones you named.

conflict.tsTypeScript
interface Scores {
  [name: string]: number;
  label: string;
}
Text
conflict.ts(3,3): error TS2411: Property 'label' of type 'string' is not assignable to 'string' index type 'number'.

The error is reasonable once you read the signature as a claim. scores["label"] would be a number according to the index signature and a string according to the property, and both cannot hold. The usual fixes are to widen the index signature to a union, as in [name: string]: number | string, or to split the object into two: a typed object for the fixed fields and a nested record for the open-ended ones.

split.tsTypeScript
interface Report {
  label: string;
  scores: Record<string, number>;
}

const report: Report = { label: "week 1", scores: { ada: 9, linus: 7 } };
console.log(report.label, report.scores.ada);
Text
week 1 9

Splitting is almost always cleaner. The union widening gives callers a type they have to narrow every time they read a value, which pushes the cost of the mix onto every use site. A nested record keeps both halves precise.

Making missing keys visible

The type number for a key that may not exist is the main weakness of index signatures. The noUncheckedIndexedAccess compiler option addresses it. When enabled, any read through an index signature produces the value type plus undefined. The option is described in the TSConfig reference.

unchecked.tsTypeScript
const stock: Record<string, number> = { apples: 3 };
const n: number = stock.pears;
Text
unchecked.ts(2,7): error TS2322: Type 'number | undefined' is not assignable to type 'number'.

This output assumes noUncheckedIndexedAccess is on. With the flag off, the file compiles and n is quietly undefined at runtime. With it on, you must handle the missing case, and the usual forms are a check, a default or an explicit throw.

handled.tsTypeScript
const stock: Record<string, number> = { apples: 3 };

function count(item: string): number {
  const n = stock[item];
  if (n === undefined) {
    return 0;
  }
  return n;
}

console.log(count("apples"), count("pears"));
Text
3 0

The same flag also affects arrays, so list[0] becomes T | undefined. Some teams find that noisy in loops and turn it off. If your code leans on dictionaries, leave it on: it is the one setting that makes the type match the runtime.

Template literal keys

Since TypeScript 4.4, an index signature can use a template literal pattern as the key type. That lets you describe an object where only keys of a certain shape are open-ended.

pattern.tsTypeScript
const attrs: { [key: `data-${string}`]: string } = {};

attrs["data-id"] = "7";
attrs["data-role"] = "admin";

console.log(Object.keys(attrs).join(","));
Text
data-id,data-role

Keys that do not start with data- are not covered by the signature, so the compiler does not let you treat them as part of this type. This is useful for HTML attributes, CSS custom properties that start with --, and event names with a common prefix. You can combine a pattern signature with named properties, because the named ones only need to fit the pattern signatures whose patterns they match.

Inherited keys and the prototype

A plain object created with {} inherits from Object.prototype, which means keys such as constructor and toString exist on it even when you never set them. An index signature does not know about that.

proto.tsTypeScript
const counts: Record<string, number> = {};
console.log(typeof counts["constructor"]);

const safe = new Map<string, number>();
console.log(safe.get("constructor"));
Text
function
undefined

The type of counts["constructor"] is number, and the runtime value is a function. Any code that uses user-supplied words as keys can run into this: counting the words in a text and meeting the word "constructor" gives NaN after counts[word]++. A Map has no such problem, because its keys live in their own table and are not mixed with inherited properties.

When to use a Map instead

Index signatures describe plain objects, and plain objects are the right shape for data that is serialised to JSON, for small fixed vocabularies and for configuration. They are the wrong shape for a collection that grows and shrinks over time, for keys that are not strings, and for any case where keys come from untrusted input.

Reach for a Map when:

  • keys are added and removed often, because Map is built for that and keeps insertion order

  • keys come from outside your program, such as words in a document or ids in a request

  • keys are objects or numbers that should not be coerced to strings

  • you need the size without counting keys

Stay with an object and an index signature when the data goes straight to JSON.stringify, when you want object spread and destructuring, or when a short literal reads better than a series of set calls. If you do use an object for untrusted keys, create it with Object.create(null) or check with Object.hasOwn before reading.

Testing the shape of a record

A record-typed value is easy to test because the interesting behaviour is at the boundary: what happens for a key that is not there. A test for the count function above would assert the present case, the missing case and a key named constructor. The last one is the test that catches the prototype problem, and it is cheap to add. For lookup tables over a union of literals, a type-level test is enough: if the table compiles, it is complete. Adding a member to the union and watching the build fail in every table is the test, and you did not have to write it.

A closing checklist

Before you write an index signature, ask what the keys are. If you can list them, use a union of literals with Record or a mapped type, and let the compiler enforce completeness. If they are open-ended, use Record<string, T> and turn on noUncheckedIndexedAccess so that every read admits it may miss. If the keys are untrusted or change often, use a Map. If a type needs both fixed fields and open-ended ones, separate them into two properties instead of fighting error TS2411. These four choices cover almost every case, and they make the types say what the objects really do.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.