TypeScript Record Type
Record<Keys, Type> is a utility type that constructs an object type whose property keys are Keys and whose property values are Type. It is one of the most useful utilities for defining dictionaries, maps, or objects with a fixed set of keys.
1. Syntax
Record<Keys, Type>
- Keys: Can be
string,number,symbol, or a union of literals (e.g.,"a" | "b"). - Type: The type of value associated with each key.
2. Basic Usage: Dictionaries
If you need an object where keys are arbitrary strings and values are numbers (a dictionary), Record is a cleaner alternative to index signatures.
// Old way (Index Signature)
type Scores = { [name: string]: number };
// New way (Record)
type Scores = Record<string, number>;
const gameScores: Scores = {
"Alice": 10,
"Bob": 20
};
3. Restricting Keys (Unions)
The real power of Record appears when Keys is a union of specific strings. TypeScript enforces that all keys in the union must be present in the object.
type Page = "home" | "about" | "contact";
interface PageInfo {
title: string;
}
const nav: Record<Page, PageInfo> = {
home: { title: "Home" },
about: { title: "About Us" },
contact: { title: "Contact" }
};
// Error: Property 'contact' is missing in type...
// const incompleteNav: Record<Page, PageInfo> = {
// home: { title: "Home" },
// about: { title: "About Us" }
// };
4. Using Enums as Keys
Record is excellent for mapping Enum values to configuration objects.
enum Role {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
}
const permissions: Record<Role, string[]> = {
[Role.Admin]: ["create", "read", "update", "delete"],
[Role.User]: ["read", "create"],
[Role.Guest]: ["read"]
};
5. Use Case: Mapping IDs to Objects
A common pattern in state management (like Redux) is normalizing data by ID.
interface User { id: string; name: string; }
type UserMap = Record<string, User>;
const usersById: UserMap = {
"u1": { id: "u1", name: "Alice" },
"u2": { id: "u2", name: "Bob" }
};
programming/javascript/typescript/typescript programming/javascript/typescript/utility-types