TypeScript Record

Since TypeScript v2.1, the Record type creates an object type where the keys of the object are of a specified type, and the values associated with those keys are of another specified type.

1. Syntax

The basic syntax for creating a Record is:

type MyRecord = Record<KeyType, ValueType>;

Where the syntax contains:

  • MyRecord: The name of the custom record type.
  • KeyType: The type of the keys of the object.
  • ValueType: The type of the values associated with those keys.

2. Creating a Record

In TypeScript, a Record is created in the dictionary style using the curly braces and specifying the types of the keys and the values.

In the following TypeScript Record example, keys are always string type and values can be either number or string types.

type Author = Record<string, number | string>;

const lokesh: Author = {  // first record
    id : 1,
    name : "Lokesh"
};

const amit: Author = {  // second record
    id : 2,
    name : "Amit"
}

We can also create records with complex types. For example, in the following code, we are creating a Record of Author instances.

type AuthorList = Record<string, Author>;

const authors: AuthorList = {
	admin: lokesh,
	editor: amit
};

3. Retrieve, Add, Modify and Delete Operations

The keys and values of a Record can be accessed and modified using the dot (.) notation. The following operations are possible in a Record type:

  • Get the value associated with the specified key
  • Add a new key-value to the record
  • Modify an existing value for the specified key in the record
  • Delete the specified key (and associated value) from the record

The following example gets the value of “id“, adds a new key “age” to the record, modifies the value for existing key “name” and finally deletes the key “id“.

type Author = Record<string, number | string>;

const lokesh: Author = {
  id: 1,
  name: "Lokesh"
};

// Get the value associated with key
const authorId = lokesh.id;		    // authorId is 1						           

// Adding a new key-value pair
lokesh.age = 30;					// lokesh  = { id: 1, name: 'Lokesh', age: 30 }

// Modifying a key's value
lokesh.name = "Lokesh Gupta";		// lokesh = { id: 1, name: 'Lokesh Gupta', age: 30 }

// Removing a key-value pair
delete lokesh.id;  					// lokesh = { name: 'Lokesh G', age: 30 }

4. Iterating Over Keys and Values of a Record

We can iterate over the keys and values of a TypeScript record in a ‘for...in‘ loop or by using the Object.entries() method.

The following example iterates over the record keys and values using the for…in loop:

type Author = Record<string, number | string>;

const lokesh: Author = {
  id: 1,
  name: "Lokesh"
};

for (const key in lokesh) {

  console.log("Key:", key);
  console.log("Value:", lokesh[key]);
}

The program output:

[LOG]: "Key:",  "id" 
[LOG]: "Value:",  1 
[LOG]: "Key:",  "name" 
[LOG]: "Value:",  "Lokesh" 

Similarly, the next example iterates over the record keys and values using the Object.entries() method:

Object.entries(lokesh).forEach(([key, value]) => {

  console.log("Key:", key);
  console.log("Value:", value);
});

The program output:

[LOG]: "Key:",  "id" 
[LOG]: "Value:",  1 
[LOG]: "Key:",  "name" 
[LOG]: "Value:",  "Lokesh" 

5. Check if Specified Key Exists in the Record

To write a bug-free code, it is very important to test that if a key exists in the Record before accessing and using its associated value. We can check the existence of a specified key using either ‘hasOwnProperty()‘ method or the ‘in‘ operator.

The following example checks if the keys “name” and “location” exist for the Author record.

const lokesh: Author = {
  id: 1,
  name: "Lokesh"
};

if (lokesh.hasOwnProperty("name")) {
  console.log(`Key "name" exists in the record.`);
} else {
  console.log(`Key "name" does not exist in the record.`);
}

if (lokesh.hasOwnProperty("location")) {
  console.log(`Key "location" exists in the record.`);
} else {
  console.log(`Key "location" does not exist in the record.`);
}

The program output:

[LOG]: Key "name" exists in the record.
[LOG]: Key "location" does not exist in the record.

Similarly, we can use the ‘in‘ operator to check for key existence as follows:

type Author = Record<string, number | string>;

const lokesh: Author = {
  id: 1,
  name: "Lokesh"
};

if ("name" in lokesh) {
  console.log(`Key "name" exists in the record.`);
} else {
  console.log(`Key "name" does not exist in the record.`);
}

if ("location" in lokesh) {
  console.log(`Key "location" exists in the record.`);
} else {
  console.log(`Key "location" does not exist in the record.`);
}

The program output:

[LOG]: Key "name" exists in the record.
[LOG]: Key "location" does not exist in the record.

6. Conclusion

Clearly demonstrated above, the Record utility type in TypeScript provides a powerful tool for defining objects with specified key-value types and helps in achieving the required type safety in the program.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode