Record
type Record<K extends keyof any, T> = {
[P in K]: T;
};Construct an object type with keys K and values T. This is a type-level mapped type. It does not construct a value and it does not check data at runtime.
| Type parameter | Description |
|---|---|
K | A key type, constrained to keyof any (string | number | symbol). A literal union lists required keys. string describes an open dictionary. |
T | The value type for each key. Record does not accept a per-key value type; use a plain object type or a mapped type when keys need different value types. |
Produces: An object type. No runtime object is created by the alias itself.
Type errors
type error— When K is a literal union, omitting one of those keys is a type error. Assigning a value of the wrong type to a known key is also a type error. JSON.parse is typed as any, so a later annotation of Record<string, number> is not checked against the parsed payload.
- In this example, JSON.parse('{"port":"80"}') is annotated as Record<string, number>, but the runtime value of port is the string "80". typeof confirms there is no runtime check.
- To reject that payload, check the value at runtime, as in the overview recipe on validating parsed JSON. A type annotation is not a validator.
type Ports = Record<"http" | "https", number>;
const ports: Ports = { http: 80, https: 443 };
// @ts-expect-error Record requires a property for every key in the union
const missing: Ports = { http: 80 };
const counts: Record<string, number> = { a: 1 };
counts.b = 2;
const parsed: Record<string, number> = JSON.parse('{"port":"80"}');
console.log(ports.https, counts.b, typeof parsed.port, parsed.port);Expected output
443 2 string 80