Complete lookup tables
Represent a finite set of named entries, such as routes or feature flags, while requiring every declared key.
TypeScript · Type Alias
Record<Keys, Type> constructs an object type whose keys come from Keys and whose values all use Type. It is useful for strongly typed dictionaries and lookup tables.
Record<Keys, Type> creates an object type with one property for every key in Keys, assigning Type as the value type for each property. It is useful when a known set of property names must all share a value shape.
Record<Keys, Type>| Name | Type | Description |
|---|---|---|
Keys | Keys | The property-key type used to determine the object’s keys. |
Type | Type | The type assigned to every property in the resulting object. |
An object type with properties keyed by Keys and values of Type.
type Page = "home" | "about" | "contact";
type PageInfo = {
title: string;
url: string;
};
const pages: Record<Page, PageInfo> = {
home: { title: "Home", url: "/" },
about: { title: "About", url: "/about" },
contact: { title: "Contact", url: "/contact" }
};
console.log(pages.about.url);The union supplies the required keys, while PageInfo describes the value stored under each key.
Represent a finite set of named entries, such as routes or feature flags, while requiring every declared key.
Give every property in a key union the same object, primitive, or function value type.
Transform values associated with a known key set from one type to another.
Record<K, T> describes an object whose keys are K and whose values are T. If K is a union, each member becomes a required property in the resulting object type.
Follow-up: How does Record differ from a mapped type over an existing type? Record creates properties from its key type rather than copying properties and their modifiers from an input type.
A union such as "home" | "about" | "contact" constrains the permitted property names. The value type is applied uniformly to every one of those properties.
Follow-up: What happens when a key is omitted from an object assigned to Record<K, T>? The assignment fails because the mapped key set requires that property.
Record is globally available as a TypeScript utility type and was released in TypeScript 2.1. It is intended for common object-type transformations and does not require an import.
Follow-up: When would an index signature be less precise? An index signature can allow arbitrary keys, whereas Record with a literal-key union restricts the object to the declared key set.
PickPartialReadonlymapped typesindex signatures