Utility type record in TypeScript
Record is a utility type in TypeScript that allows creating a new object type with specific keys and values. It provides a convenient way to define a type for objects where keys can be limited to specific values, and values have a certain type.
Syntax:
typescript
Record<K, T>K— type of object keys (e.g., strings or numbers).T— type of values corresponding to these keys.
The Record type allows defining that an object must have a certain set of keys and values, making it very useful when working with predefined keys and value types.
Record Usage Example
- Creating an object with predictable keys and values:
Suppose we have a list of roles in an application, and we want to create an object where each key (role) corresponds to an array of strings representing user permissions.
typescript
type UserRoles = "admin" | "user" | "guest";
type RolePermissions = Record<UserRoles, string[]>;
const rolePermissions: RolePermissions = {
admin: ["create", "edit", "delete"],
user: ["view", "edit"],
guest: ["view"],
};UserRolesis a type representing user roles (e.g.,"admin", "user", "guest").Record<UserRoles, string[]>creates an object where keys are strings corresponding to roles, and values are arrays of strings containing access permissions for each role.- Using Record to create objects with dynamic keys: You can use Record to create objects with dynamic keys, for example, based on enum values.
typescript
enum Status {
Active = "active",
Inactive = "inactive",
Pending = "pending",
}
type StatusMessage = Record<Status, string>;
const statusMessages: StatusMessage = {
[Status.Active]: "Your account is active.",
[Status.Inactive]: "Your account is inactive.",
[Status.Pending]: "Your account is pending approval.",
};Statusis an enum representing possible statuses.Record<Status, string>creates an object where keys are values from the Status enum, and values are strings representing messages for each status.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.