Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 96 ยท Basic Types

Index Signatures and Record

Type dynamic-key objects in TypeScript - string, number, symbol and template-literal index signatures, Record<K, V>, Map vs object, noUncheckedIndexedAccess.

The object types in the previous lesson list every property by name. That works for a user or an order, but not for a word counter, a cache keyed by ID, a table of translations or a bag of HTTP headers. In those objects the keys are data: you don't know them when you write the code, only what kind of value sits behind each one.

TypeScript describes these "dictionary" objects with index signatures and the built-in Record<K, V> type. This lesson shows both, explains the one big trap (reading a missing key), and helps you decide when a JavaScript Map is the better choice.

Index signatures

An index signature looks like a property whose name is a placeholder in square brackets:

TypeScript
type Scores = { [player: string]: number };

Read it as "for any string key, the value is a number". The name player is only a label for readers; it has no effect on the type, so pick something descriptive (key is fine when nothing better fits).

TypeScript A word counter with an index signature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program prints the whole object, then 2 2, then the two repeated words. Both dot access (counts.cat) and bracket access (counts['the']) are allowed, because every string key is valid. Object.entries() gives [string, number][], so n is a number inside the loop.

Writing a value of the wrong type is still an error. counts.dog = 'many' would fail with TS2322, exactly as with a normal property.

The trap: missing keys

Look again at counts[word] ?? 0 in the example. Why the ?? 0? Because a key that was never set gives undefined at runtime. But by default, TypeScript says reading an index signature gives the value type, number, with no undefined:

TypeScript Reading a key that does not exist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

kiwi + 1 prints NaN, and TypeScript said nothing. The type system assumed the key exists because an index signature promises a value for every string. That's convenient for code that just wrote the key, but dangerous for lookups.

noUncheckedIndexedAccess

The compiler option noUncheckedIndexedAccess fixes the trap: with it, reading through an index signature (or an array index) gives T | undefined, and TypeScript makes you handle the missing case.

JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}
TypeScript
// With noUncheckedIndexedAccess on:
const stock: { [sku: string]: number } = { apple: 12 };
const kiwi = stock['kiwi'];   // number | undefined
kiwi + 1;                     // error TS18048: 'kiwi' is possibly 'undefined'.
const safe = (stock['kiwi'] ?? 0) + 1;  // OK

It isn't part of --strict, and our editor's options are fixed without it. You can get the same safety for one type by putting undefined in the value type yourself, which is a useful technique even in projects without the flag:

TypeScript Honest lookups without the flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints 3.5 and then No price for soup. The if check narrows price from number | undefined to number, a technique explained in Narrowing. (The e as Error is a type assertion; Error Handling shows safer ways to handle caught errors.)

If you start a new project, turn on noUncheckedIndexedAccess. It catches real bugs in lookups and array indexing for very little extra code. The tsconfig.json File lists it among the recommended options.

Mixing known properties with an index signature

An object type can have named properties and an index signature. The rule: every named property must fit the index signature's value type, because the index signature claims to describe all string keys, including the named ones.

TypeScript Named properties plus an index signature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is application/json, 3 and the config object. If the index signature in Config were just [option: string]: boolean, the named property name: string would conflict with it:

TypeScript A property that conflicts (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(2,3): error TS2411: Property 'name' of type 'string' is not assignable to 'string' index type 'boolean'.
main.ts(6,7): error TS2322: Type '{ name: string; debug: true; }' is not assignable to type 'Flags'.
  Property 'name' is incompatible with index signature.
    Type 'string' is not assignable to type 'boolean'.

The first error is about the type itself; the second appears because no object can satisfy a contradictory type.

When you see TS2411, either widen the index signature's value type, or (often better) move the dynamic part into its own property: { name: string; flags: { [flag: string]: boolean } }. Keeping fixed and dynamic data apart makes both easier to type.

Number, symbol and template-literal keys

Besides string, an index signature's key type may be number, symbol, a template literal pattern, or a union of these.

Number keys. { [index: number]: T } describes array-like objects. JavaScript converts number keys to strings (obj[1] and obj['1'] are the same property), so a number index signature is really a promise about numeric-looking string keys. If a type has both a string and a number index signature, the number one's value type must fit the string one's.

Symbol keys. { [key: symbol]: T } types objects that use symbols as keys, which is rare outside libraries.

Template-literal keys. A pattern like `data-${string}` matches only keys with that prefix. This is great for objects that mix fixed properties with a family of prefixed ones:

TypeScript Number and template-literal index signatures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints three numbered column names, then u42 false, then 1234. With ElementProps, a key such as 'dataUser' would be an excess property error, because it matches neither a named property nor the data- pattern. You'll meet template literal types properly in Template Literal Types.

Record<K, V>

Record<K, V> is a built-in utility type that builds an object type from a key type K and a value type V. With string keys, it's just a shorter spelling of an index signature:

TypeScript
type A = { [key: string]: number };
type B = Record<string, number>;   // the same thing

Record becomes really useful when K is a union of specific keys. Then the type requires every key, and nothing else, which is perfect for lookup tables:

TypeScript Record with a union of keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is 6.5, [ 'small', 'medium', 'large' ] and { canEdit: true, canDelete: false }. Here, reading priceBySize[size] is safe even with noUncheckedIndexedAccess, because the keys are a finite set and all of them must exist.

That completeness is checked. If someone adds 'xl' to Size later, every Record<Size, ...> in the codebase becomes an error until the new key is filled in:

TypeScript A missing key in a Record (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(3,7): error TS2741: Property 'xl' is missing in type '{ small: string; medium: string; large: string; }' but required in type 'Record<Size, string>'.

Only one error: the second object is fine, because Partial<...> makes every key optional. Partial<Record<K, V>> is the standard way to say "some of these keys, maybe". Both Partial and Record are covered with the other helpers in Built-in Utility Types, and you can learn how they're built in Mapped Types.

Why Object.keys() returns string[]

A common surprise: Object.keys(priceBySize) has the type string[], not Size[]. That's deliberate. TypeScript's object types are open: a value may carry extra properties that its type doesn't mention (you saw this with excess properties in Object Types). So TypeScript can't promise that the keys are only the ones in the type.

TypeScript
const keys = Object.keys(priceBySize);   // string[]
for (const key of keys) {
  // priceBySize[key];  // error TS7053: Element implicitly has an 'any' type
  //                    // because expression of type 'string' can't be used to index type 'Record<Size, number>'.
}

When you control the object and know it has no extras, you can loop over a list of the keys you own instead (const sizes = ['small', 'medium', 'large'] as const) or use Object.entries(), which gives the values with the right type. Avoid casting Object.keys(x) as (keyof typeof x)[] everywhere; it's an assertion that hides the open-object risk. keyof, typeof and Indexed Access Types explains keyof in depth.

Map or object?

JavaScript also has Map (see maps in the JavaScript course), and TypeScript types it as Map<K, V>. Its get() method is honest from the start: it returns V | undefined.

TypeScript The same lookup with a Map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints 0 (note that ?? keeps 0, unlike ||), not stocked, 3 3, and then the Map as Node shows it: Map(3) { 'apple' => 12, 'pear' => 0, 'kiwi' => 7 }.

How to choose:

Plain object + index signature / Record Map<K, V>
Key types strings (and numbers/symbols) anything, including objects
Missing key type V (unless noUncheckedIndexedAccess) always V | undefined
JSON works directly with JSON.stringify needs conversion
Fixed set of keys Record<'a' | 'b', V> checks completeness not checked
Frequent add/delete, size possible but clumsy built for it (size, delete, ordered)
Prototype keys like 'constructor' can collide no collisions

A good rule of thumb: use Record<Union, V> for fixed lookup tables and configuration, objects for data that becomes JSON, and Map for dynamic collections that grow and shrink at runtime.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With default strict settings, what is the type of x in const m: { [k: string]: number } = {}; const x = m.anything;?

    An index signature promises a value for every string key, so reads give number. Only noUncheckedIndexedAccess adds undefined.
  2. 2. Does type T = { id: number; [k: string]: string }; compile?

    Every named property must be assignable to the string index signature's value type. Widen it to string | number or move the dynamic keys elsewhere.
  3. 3. Given type Size = 's' | 'm', which value is valid for Record<Size, number>?

    A Record over a union of keys requires every key and rejects unknown ones in a fresh literal. Use Partial<Record<Size, number>> to make keys optional.
  4. 4. Why is Object.keys(obj) typed as string[] rather than an array of the object's known keys?

    Structural typing allows extra properties, so TypeScript can't promise the keys are only the declared ones.
  5. 5. What does new Map<string, number>().get('a') return as a type?

    Map.get is typed honestly from the start; it returns V | undefined because the key may be missing.

Summary

  • An index signature { [key: string]: T } types objects whose keys are data. The key name is just a label.
  • By default, reading any key gives T, even when the key doesn't exist. Turn on noUncheckedIndexedAccess, or use T | undefined as the value type, to make lookups honest. Check with in, Object.hasOwn() or ??.
  • Named properties alongside an index signature must fit its value type (TS2411). Often it's cleaner to keep fixed and dynamic data in separate properties.
  • Keys can also be number, symbol or template-literal patterns such as `data-${string}`.
  • Record<string, V> equals a string index signature; Record<'a' | 'b', V> requires exactly those keys, and Partial<Record<K, V>> makes them optional.
  • Object.keys() returns string[] because object types are open.
  • Prefer Map<K, V> for dynamic collections with any key type; its get() returns V | undefined.

Next: any, unknown, never and void