Record<Keys, Type>
Creates an object type with given keys, where every value has the same type.
Example
#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)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
#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
#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,
Recordenforces 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
#- Index signatureA description of objects with arbitrary keys and values of one type.
- Pick<Type, Keys>Creates a type containing only selected properties of another type.
- Mapped typesCreate a new object type by transforming every key of another type.
- keyofCreates a union of the key names of a given object type.
Spotted a mistake or missing an example? Write to us.