Record
Create an object type with specific keys all mapped to one value type.
Syntax
Record<string, number>Record<Keys, Value> builds an object type whose keys come from Keys and whose values are all of type Value. It is a clean way to describe lookup tables and dictionaries.
Reading it
Record<string, number> is an object with string keys and number values, similar to an index signature.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A translation file is typed as Record<string, string> to map arbitrary locale keys to their translated strings.
- A score board is typed as Record<string, number> where player names are the keys and scores are the values.
- A lookup table maps Status enum values to display labels using Record<Status, string>.
More examples
Record with string keys
Creates a string-to-string map with Record<string, string> and shows that value type mismatches are caught.
const translations: Record<string, string> = {
hello: 'Hola',
goodbye: 'Adios',
thanks: 'Gracias',
};
translations['welcome'] = 'Bienvenido'; // OK
translations['count'] = 42; // Error: Type 'number' is not assignableRecord with a union key type
Uses a string literal union as the key type so every possible Status value must have a corresponding entry.
type Status = 'pending' | 'active' | 'banned';
const statusLabels: Record<Status, string> = {
pending: 'Awaiting approval',
active: 'Active account',
banned: 'Account banned',
};
console.log(statusLabels['active']); // 'Active account'Record to group items by key
Builds a grouped-by-category map typed as Record<string, Product[]> using reduce with a nullish assignment initialiser.
interface Product { category: string; name: string; }
function groupBy(products: Product[]): Record<string, Product[]> {
return products.reduce<Record<string, Product[]>>((acc, p) => {
(acc[p.category] ??= []).push(p);
return acc;
}, {});
}
const grouped = groupBy([
{ category: 'books', name: 'TypeScript Handbook' },
{ category: 'books', name: 'Clean Code' },
{ category: 'tools', name: 'VS Code' },
]);
Discussion