Skip to content
DeveloperMemos

Understanding the Record Type in TypeScript

TypeScript, Record Type, Advanced Types1 min read

TypeScript's Record type is a utility type that facilitates the creation of a type with a set of properties of a certain type. This article explains what Record is and how to use it effectively in TypeScript.

What is Record in TypeScript?

The Record type is a generic utility that represents an object with keys of a certain type and values of another type. It is used to construct types with a specific set of property keys and corresponding value types.

Syntax of Record

The Record type has the following syntax:

1Record<K, T>

Here, K represents the type of keys, and T represents the type of values.

Example Usage of Record

Let's consider an example to understand Record better.

1enum Status {
2 Active,
3 Inactive,
4 Suspended
5}
6
7type UserStatusRecord = Record<Status, string>;

In this example, UserStatusRecord is a type where each key is a member of the Status enum, and each value is a string.

Creating an Object with Record

You can create an object of a Record type like any other type:

1const userStatus: UserStatusRecord = {
2 [Status.Active]: "User is active",
3 [Status.Inactive]: "User is inactive",
4 [Status.Suspended]: "User is suspended"
5};

This object adheres to the UserStatusRecord type, ensuring each key-value pair matches the defined types.

Benefits of Using Record

  • Type Safety: Record ensures that all keys and their corresponding values adhere to the specified types.
  • Code Readability: It makes the intention of your types clear and explicit.
  • Flexibility: You can use any type for keys (e.g., enum, union of literals) and values.