In TypeScript, the Record
type is a utility type that represents an object type with keys and values of a specific type. It is often used when you want to define a type for the keys and values of an object. In this article, we will learn what is the Record type in TypeScript.
Syntax:
Record<Keys, Type>
-
Keys
: A union of string literal types representing the keys of the record. -
Type
: The type that the values associated with the keys should have.
Example: In this example, Car
is a type that represents an object with keys ‘make’, ‘model’, and ‘year’, and each key must have a string value.
type Car = Record<string, string |
string |
number>;
const myCar: Car = { make: 'Toyota' ,
model: 'Camry' ,
year: 2022,
}; console.log( typeof myCar.make,
typeof myCar.model,
typeof myCar.year);
|
Output:
string string number
Use Cases
User Profile
Imagine you are developing a user management system, and you want to define the structure of a user profile. The user profile has specific properties such as ‘username’, ’email’, and ‘age’. By using the Record
type, you can ensure that instances of the user profile always have the expected properties with the correct data types.
Example: The below code example explains the use of the Record type in case of creating a user profile.
type UserProfile = Record< 'username' |
'email' |
'age' ,
string |
number>;
const validUserProfile: UserProfile = { username: 'john_doe' ,
email: 'john@example.com' ,
age: 25,
}; console.log( typeof validUserProfile.username,
typeof validUserProfile.email,
typeof validUserProfile.age)
|
Output:
string string number
Feature Flags
Consider a web application where you want to manage feature flags dynamically. Feature flags are configuration settings that control the availability of certain features. Using the Record
type, you can create a type that represents a set of feature flags with string keys and boolean values.
Example: In this use case, the FeatureFlags
type allows you to create a flexible configuration object for feature flags.
type FeatureFlags = Record<string, boolean>; const featureFlags: FeatureFlags = { enableNotifications: false ,
darkMode: true ,
// ... additional feature flags
}; console.log(featureFlags); |
Output:
{
"enableNotifications": false,
"darkMode": true
// ... additional feature flags
}