TypeScriptUtility types

Record<Keys, Type>

Creates an object type with given keys, where every value has the same type.

On this page

Example

#
TypeScript
type Course = 'html' | 'javascript' | 'python'

const modules: Record<Course, number> = {
  html: 11,
  javascript: 16,
  python: 12
}

const total = Object.values(modules).reduce((sum, n) => sum + n, 0)
console.log(total)
Result
39

Definition and usage

#

Record<Keys, Type> describes an object whose keys belong to the Keys type, and whose values all have the type Type. Record<string, number> is a dictionary of numbers, and Record<"html" | "css", number> is an object with exactly two fields.

With a union of literals as the keys, the compiler requires every field. If you add a new variant to the union, every Record using that union reports a missing field, which helps keep things consistent.

It’s a more readable alternative to the index signature { [key: string]: T }, and the go-to type for configuration maps, translations, or counters.

Syntax

#
Syntax
type New = Record<Keys, ValueType>

Type parameters

#
  • Keys

    string, number, symbol, or a union of literals

    The allowed keys.
  • Type

    any type

    The type of each value.

More examples

#
A missing key
TypeScript
const labels: Record<Course, string> = { html: 'HTML and CSS', python: 'Python' }
// Error: Property 'javascript' is missing in type '{ html: string; python: string; }'.

Good practices

#
  • With keys from a union of literals, Record enforces completeness. That’s great for maps of labels and colors.
  • For dictionaries with unknown keys, consider Map, which handles frequent additions and removals better.

Related entries

#

Spotted a mistake or missing an example? Write to us.