— TypeScript, Record Type, Advanced Types — 1 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.
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.
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.
Record
Let's consider an example to understand Record
better.
1enum Status {2 Active,3 Inactive,4 Suspended5}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.
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.
Record
Record
ensures that all keys and their corresponding values adhere to the specified types.