How to use Record type in typescript?


In TypeScript, the Record type is a powerful tool that allows you to define an object type with specific keys and corresponding value types. This tutorial will guide you through the fundamentals of using the Record type, providing syntax explanations and practical examples along the way. Whether you're a beginner or already familiar with TypeScript, this tutorial will help you understand how to leverage the Record type effectively in your projects.

Syntax

The syntax to create a Record type in TypeScript is straightforward. The type definition starts with the keyword Record, followed by angle brackets (<>) containing the key and value types enclosed in curly braces ({}). Here's an example to illustrate the syntax −

type MyRecord = Record<string, number>;

Here, we define MyRecord as a Record type with string keys and number values. Now, let's dive into different scenarios where the Record type is useful.

Example 1: Defining a Dictionary

A common use case for the Record type is creating dictionaries with specific key-value pairs. This is especially helpful when you need to organize data or access values by their respective keys. In this code snippet, we define AnimalAges as a Record type with string keys and number values. The ages object represents our dictionary, with animal names as keys and their respective ages as values. We can access the values using dot notation, as shown in the console.log statements.

type AnimalAges = Record<string, number>;
const ages: AnimalAges = {
   dog: 5,
   cat: 3,
   rabbit: 2,
};
console.log(ages.dog);
console.log(ages.cat);

On compiling, it will generate the following JavaScript code −

var ages = {
   dog: 5,
   cat: 3,
   rabbit: 2
};
console.log(ages.dog);
console.log(ages.cat);

Output

The above code will produce the following output −

5
3

Example 2: Preserving Key Types

The Record type is flexible and allows you to preserve specific key types, such as literal types. This is useful when enforcing strict key names within an object. In this example, we define FruitColors as a union type representing different fruit names. We then create a ColorsRecord using the Record type, with the fruit names as keys and string values representing their respective colors. By utilizing literal types, we ensure that only valid fruit names can be used as keys in the colors object.

type FruitColors = 'apple' | 'banana' | 'orange'; type ColorsRecord = Record<FruitColors, string>;
const colors: ColorsRecord = {
   apple: 'red',
   banana: 'yellow',
   orange: 'orange',
};

console.log(colors.apple); 
console.log(colors.banana);

On compiling, it will generate the following JavaScript code −

var colors = {
   apple: 'red',
   banana: 'yellow',
   orange: 'orange'
};
console.log(colors.apple);
console.log(colors.banana);

Output

The above code will produce the following output −

red
yellow

Example 3: Mapping and Transforming Values

The Record type can also be used to map and transform values within an object. Let's consider a scenario where we have a list of students' names and want to convert them into uppercase using the Record type. In this example, we define StudentNames as an object type with specific keys representing the students' names. We then create UppercaseNames using the Record type, ensuring that the keys are the same as those in StudentNames. By utilizing the toUpperCase() method, we transform the names to uppercase and assign them to the respective keys in the uppercaseStudents object.

type StudentNames = {
   alice: string;
   bob: string;
   charlie: string;
};

type UppercaseNames = Record<keyof StudentNames, string>;

const students: StudentNames = {
   alice: 'Alice',
   bob: 'Bob',
   charlie: 'Charlie',
};

const uppercaseStudents: UppercaseNames = {
   alice: students.alice.toUpperCase(),
   bob: students.bob.toUpperCase(),
   charlie: students.charlie.toUpperCase(),
};

console.log(uppercaseStudents);

On compiling, it will generate the following JavaScript code −

var students = {
   alice: 'Alice',
   bob: 'Bob',
   charlie: 'Charlie'
};
var uppercaseStudents = {
   alice: students.alice.toUpperCase(),
   bob: students.bob.toUpperCase(),
   charlie: students.charlie.toUpperCase()
};
console.log(uppercaseStudents);

Output

The above code will produce the following output −

{ alice: 'ALICE', bob: 'BOB', charlie: 'CHARLIE' }

Example 4: Handling Dynamic Object Keys

The Record type is especially useful when dealing with objects that have dynamic keys. Consider a scenario where we want to count the occurrences of words in a sentence. In this example, we define the countWords function that takes a sentence as input and returns a Record type, where the keys represent the unique words in the sentence, and the values represent the frequency of occurrence for each word. By splitting the sentence into an array of words and iterating over each word, we update the counts in the wordCount object accordingly.

function countWords(sentence: string): Record<string, number> {
   const words: string[] = sentence.split(' ');
   const wordCount: Record<string, number> = {};

   words.forEach((word) =< {
      if (wordCount[word]) {
         wordCount[word]++;
      } else {
         wordCount[word] = 1;
      }
   });

   return wordCount;
}

const sentence = 'This is a sentence. This sentence contains multiple words.';
const wordCount = countWords(sentence);

console.log(wordCount);

On compiling, it will generate the following JavaScript code −

function countWords(sentence) {
   var words = sentence.split(' ');
   var wordCount = {};
   words.forEach(function (word) {
      if (wordCount[word]) {
         wordCount[word]++;
      }
      else {
         wordCount[word] = 1;
      }
   });
   return wordCount;
}
var sentence = 'This is a sentence. This sentence contains multiple words.';
var wordCount = countWords(sentence);
console.log(wordCount);

Output

The above code will produce the following output −

{
   This: 2,
   is: 1,
   a: 1,
   'sentence.': 1,
   sentence: 1,
   contains: 1,
   multiple: 1,
   'words.': 1
}

Conclusion

The Record type in TypeScript provides a convenient way to define objects with specific key-value pairs. Whether you're creating dictionaries or preserving key types, the Record type offers flexibility and type safety. By understanding the syntax and exploring various scenarios; you can harness the power of the Record type to write more expressive and error-free code.

Updated on: 21-Aug-2023

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements