Have you heard about Hack Frontend Community?Join us on Telegram!
Practice TS Problems

Record<K, V> in TypeScript: Type-Safe Key-Value Objects

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:

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.

    type UserRoles = "admin" | "user" | "guest";
    type RolePermissions = Record<UserRoles, string[]>;
    
    const rolePermissions: RolePermissions = {
      admin: ["create", "edit", "delete"],
      user: ["view", "edit"],
      guest: ["view"],
    };
    
    • UserRoles is 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.

    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.",
    };
    
    • Status is 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.
Practice TS Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.