Index signatures and Record
Typing objects used as dictionaries: index signature syntax and its rules, what reading a missing key returns, and when `Record<K, V>` says it better.
Object types, optional and readonly propertiesUnion and literal types
Index signatures and Record
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An index signature such as `{ [word: string]: number }` describes an object whose keys aren't known in advance but whose values all share one type.
- Index signature keys may be `string`, `number`, `symbol`, template literal patterns like `` `data-${string}` ``, or unions of these.
- Every named property in a type with a string index signature must fit the index signature's value type, so mixing fixed fields with a dictionary usually needs a union value type.
- By default, reading any key through an index signature gives the value type with no `undefined`, even for keys that don't exist; `noUncheckedIndexedAccess` changes that.
- `Record<K, V>` is a built-in shorthand for an object with keys `K` and values `V`; with `K` as `string` it equals an index signature, and with a union of literals it requires exactly those keys.
- `Record<Status, string>` is a cheap exhaustiveness check: add a member to `Status` and every map built from it fails to compile until the new key is filled in.
Objects used as lookup tables
Most object types you’ve written so far list their properties by name: a User has an id and a name. But JavaScript code constantly uses plain objects as dictionaries, where the keys are data rather than design. Word counts keyed by word. Feature flags keyed by flag name. Translations keyed by message ID.
You can’t list those keys in a type because you don’t know them when you write the code. What you do know is the shape of every value. An index signature is how you say exactly that.
Index signature syntax
interface WordCounts {
[word: string]: number;
}
const counts: WordCounts = {};
counts["hello"] = 1;
counts.world = 2;
Read [word: string]: number as “any string key maps to a number”. The name word is only documentation. It shows up in hovers and has no other effect.
Keys can be string, number, symbol, a union of those, or a template literal pattern:
type DataAttrs = { [attr: `data-${string}`]: string };
const ok: DataAttrs = { "data-id": "42" };
const bad: DataAttrs = { id: "42" };
// Error: Object literal may only specify known properties, and '"id"' does not exist in type 'DataAttrs'.
Index signatures can be readonly, which forbids writes through any key:
interface Frozen { readonly [k: string]: number }
declare const f: Frozen;
f.total = 1;
// Error: Index signature in type 'Frozen' only permits reading.
Rules when signatures and properties mix
Named properties must fit the signature. A string index signature is a promise about every string key, and named properties are string keys:
interface Bag {
[k: string]: string;
length: number;
}
// Error: Property 'length' of type 'number' is not assignable to 'string' index type 'string'.
Widen the value type to string | number, or better, keep the dictionary in its own property so the fixed fields stay precise.
Numeric keys are string keys. At runtime obj[1] and obj["1"] read the same property, because JavaScript converts property keys to strings. So if a type has both kinds of signature, the number signature’s value type must be assignable to the string one’s:
interface Mixed {
[i: number]: string;
[k: string]: number;
}
// Error: 'number' index type 'string' is not assignable to 'string' index type 'number'.
The missing-key trap
const n = counts["missing"]; // type: number
At runtime n is undefined. The compiler says number because the signature says every key maps to a number, and it has no way to know which keys exist. It’s like a phone book that claims to list everyone: the lookup always “succeeds” on paper.
The noUncheckedIndexedAccess flag fixes this by adding | undefined to every index-signature read, so you have to check before you use the value. It’s not part of strict, and the compiler flags lesson covers when it’s worth turning on.
Record<K, V>
Record is a built-in generic type that means “an object whose keys are K and whose values are V”. With string keys it’s just another spelling of an index signature:
type Counts = Record<string, number>; // same as { [k: string]: number }
Where it earns its place is with a union of literal keys. Then it isn’t a dictionary at all. It’s an object with exactly those properties, all required:
type Status = "idle" | "loading" | "error";
const labels: Record<Status, string> = {
idle: "Idle",
loading: "Loading…",
};
// Error: Property 'error' is missing in type '{ idle: string; loading: string; }'
// but required in type 'Record<Status, string>'.
That makes Record a cheap exhaustiveness check. Add "done" to Status and every Record<Status, ...> in the codebase fails to compile until someone supplies a label. If only some keys are needed, wrap it: Partial<Record<Status, string>> still rejects unknown keys but makes each one optional. Partial and its relatives are covered in utility types for objects.
Choosing between them
- Keys come from a fixed union you control:
Record<Union, V>. - Keys are open-ended data: either
Record<string, V>or an index signature. They’re equivalent; many teams preferRecordfor brevity and an index signature when the key name helps documentation. - A type mixes fixed fields with arbitrary keys: an index signature inside an interface, with a value type that fits both.
- Keys are added and removed constantly at runtime, or aren’t strings: consider a
Map<K, V>, which also hashas()for the missing-key problem.
One related surprise: an interface without an index signature isn’t assignable to Record<string, unknown>, while an equivalent object-type alias is. The type aliases vs interfaces lesson explains why.
About the video
Dave Gray’s tutorial, part of his TypeScript course, builds the case for index signatures from a concrete problem: accessing object properties with a key held in a variable. He covers the syntax, readonly, what happens with keys that don’t exist, and combining required and optional properties with a signature, then compares index signatures with Record in the last section. The middle section on keyof assertions goes beyond this lesson; that operator gets full treatment in keyof and typeof type operators. The video doesn’t mention noUncheckedIndexedAccess, so keep the missing-key section above in mind while watching.
Check yourself
Why does `interface Bag { [k: string]: string; length: number }` fail to compile, and how would you fix it?
A string index signature promises that every string key maps to a `string`, and `length` is a string key mapping to a `number`, which breaks that promise. Widen the index signature's value type to `string | number`, or move the dictionary part into its own property such as `items: { [k: string]: string }`.
With `const counts: { [word: string]: number } = {}`, what type does `counts["missing"]` have, and why is that a risk?
Under default settings it's `number`, even though at runtime the value is `undefined`. The compiler can't know which keys exist, so it trusts the signature, and arithmetic on the result can silently produce `NaN`. Turning on `noUncheckedIndexedAccess` makes the type `number | undefined` and forces a check.
What's the difference between `Record<string, string>` and `Record<"en" | "fr", string>`?
`Record<string, string>` is an open dictionary, identical to `{ [k: string]: string }`, so any key is allowed and none are required. `Record<"en" | "fr", string>` has exactly two required properties, `en` and `fr`; leaving one out or adding another key in a literal is an error.
You want a map that may hold labels for only some members of `type Status = "idle" | "loading" | "error"`. What type do you write?
`Partial<Record<Status, string>>`. The `Record` limits the keys to the members of `Status`, and `Partial` makes each of them optional, so `{ idle: "Idle" }` is valid but an unknown key like `done` is still rejected.
Why can a `number` index signature and a `string` index signature not have unrelated value types in the same type?
JavaScript converts numeric keys to strings, so `obj[1]` and `obj["1"]` read the same property. A numeric key is therefore also a string key, and its value type must be assignable to the string index signature's value type.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.