JavaScript

TypeScript Record

TypeScript 2.1 introduced the transformative Record utility type, a dynamic tool empowering developers to construct objects with defined key-value pairs. By enhancing the language’s expressiveness, TypeScript Record fosters cleaner, error-resistant code, providing developers with a robust mechanism to handle dynamic object structures with confidence and precision. Let us understand the TypeScript Record in detail.

1. What is TypeScript?

TypeScript is a popular open-source programming language developed by Microsoft. It is a superset of JavaScript, adding optional static typing to the dynamic language. This means developers can write safer and more maintainable code by specifying data types for variables, function parameters, and return values. TypeScript code is compiled into plain JavaScript, ensuring compatibility with all JavaScript environments. It enhances productivity by providing features like type checking, interfaces, and advanced tooling for large-scale applications. TypeScript also supports modern ECMAScript features and can be used for both front-end and back-end development, making it a versatile choice for building robust and scalable web applications.

1.1 What is a Record?

TypeScript 2.1 introduced the Record utility type, a powerful tool for defining object types with specific keys and value types. This utility is particularly useful for creating dictionaries or map-like structures in a type-safe manner.

The syntax for using Record is Record<K, T>, where K represents the type of keys, and T represents the type of values. This ensures that objects created with Record adhere to a predefined structure, providing developers with static type-checking benefits.

Here’s a basic example:

Code snippet

// TypeScript 2.1 and later
type MyRecord = Record<string, number>;

const myObject: MyRecord = {
  key1: 10,
  key2: 20,
  key3: 30,
};
// TypeScript enforces that keys must be strings and values must be numbers.

The Record utility type enhances TypeScript’s ability to express and enforce object shapes, contributing to more robust and type-safe code.

2. Creating a Record

In TypeScript, you can create a Record type using the utility type provided by the language. The Record type allows you to define an object type with specific keys and a uniform value type associated with those keys.

Here’s an example of how to create a TypeScript Record:
Code snippet

// Define a Record type with string keys and number values
type MyRecord = Record;

// Create an object that adheres to the MyRecord type
const myObject: MyRecord = {
  key1: 10,
  key2: 20,
  key3: 30,
};

// TypeScript enforces that keys must be strings and values must be numbers

In this example:

  • type MyRecord = Record<string, number> defines a type MyRecord with string keys and number values.
  • const myObject: MyRecord declares an object myObject that adheres to the MyRecord type. The keys are strings, and the values are numbers.

TypeScript will enforce the specified structure, providing type safety. If you try to assign a value of the wrong type to a key or add a key that is not a string, TypeScript will raise a compilation error.

3. Retrieve, Add, Modify, and Delete Operations

Below are examples of retrieve, add, modify, and delete operations using TypeScript showcasing TypeScript’s ability to provide static type-checking, improve code robustness, and prevent potential runtime errors associated with incorrect data types.

3.1 Retrieve operation

The retrieve operation involves accessing a specific value from the object using its key. In TypeScript, the type of the value retrieved is known and can be used for type-checking, ensuring that the retrieved value adheres to the specified type.

Code snippet

// Define a Record type with string keys and number values
type MyRecord = Record;

// Sample object
const myObject: MyRecord = {
  key1: 10,
  key2: 20,
  key3: 30,
};

// Retrieve operation
const valueForKey2: number | undefined = myObject['key2'];
console.log('Retrieve Operation:', valueForKey2); // Output: 20

3.2 Add operation

The add operation involves adding a new key-value pair to the object. In TypeScript, this operation maintains type safety, ensuring that the assigned value is of the correct type according to the object’s definition.

Code snippet

// Add operation
myObject['key4'] = 40;

console.log('Add Operation:', myObject);
// Output: { key1: 10, key2: 20, key3: 30, key4: 40 }

3.3 Modify operation

The modify operation involves changing the value associated with an existing key in the object. TypeScript enforces type consistency, preventing the assignment of values that don’t match the specified type for that key.

Code snippet

// Modify operation
myObject['key2'] = 25;

console.log('Modify Operation:', myObject);
// Output: { key1: 10, key2: 25, key3: 30, key4: 40 }

3.4 Delete operation

The delete operation removes a key-value pair from the object. TypeScript ensures that only valid keys can be deleted, maintaining type integrity throughout the process.

Code snippet

// Delete operation
delete myObject['key3'];

console.log('Delete Operation:', myObject);
// Output: { key1: 10, key2: 25, key4: 40 }

4. Iterating Over Keys and Values of a Record

Iterating over keys and values of a Record in TypeScript can be achieved using various methods. Below are examples of iterating over keys and values using for...in loop and Object.entries().

4.1 Iterating Over Keys and Values with for…in

The for...in loop is a classic method for iterating over an object’s enumerable properties. In TypeScript, it’s important to use hasOwnProperty to ensure that only the object’s properties (not inherited ones) are considered. This loop allows you to access keys directly and subsequently retrieve their associated values.

Code snippet

// Define a Record type with string keys and number values
type MyRecord = Record;

// Sample object
const myObject: MyRecord = {
  key1: 10,
  key2: 20,
  key3: 30,
};

// Iterating over keys
console.log('Iterating Over Keys:');
for (const key in myObject) {
  if (myObject.hasOwnProperty(key)) {
    console.log(key);
  }
}

// Iterating over values
console.log('\nIterating Over Values:');
for (const key in myObject) {
  if (myObject.hasOwnProperty(key)) {
    console.log(myObject[key]);
  }
}

4.2 Iterating Over Keys and Values with Object.entries()

The Object.entries() method provides a modern and concise way to iterate over the key-value pairs of an object. It returns an array where each element is a two-element array representing a key-value pair. The forEach loop allows you to destructure these pairs into separate variables (key and value), making it easy to work with both components during the iteration.

Code snippet

// Iterating over keys and values using Object.entries()
console.log('\nIterating Over Keys and Values:');
Object.entries(myObject).forEach(([key, value]) => {
  console.log(`Key: ${key}, Value: ${value}`);
});

5. Check if the Specified Key Exists in the Record

To check if a specified key exists in a TypeScript Record, you can use the hasOwnProperty method or the in operator.

Here’s an example using both approaches:

Code snippet

// Define a Record type with string keys and number values
type MyRecord = Record;

// Sample object
const myObject: MyRecord = {
  key1: 10,
  key2: 20,
  key3: 30,
};

// Check if the specified key exists using hasOwnProperty
const specifiedKey = 'key2';
if (myObject.hasOwnProperty(specifiedKey)) {
  console.log(`Key '${specifiedKey}' exists with value ${myObject[specifiedKey]}`);
} else {
  console.log(`Key '${specifiedKey}' does not exist`);
}

// Check if the specified key exists using 'in' operator
const anotherKey = 'key4';
if (anotherKey in myObject) {
  console.log(`Key '${anotherKey}' exists with value ${myObject[anotherKey]}`);
} else {
  console.log(`Key '${anotherKey}' does not exist`);
}

In this example:

  • The hasOwnProperty method checks if the specified key exists directly on the object.
  • The in operator checks if the specified key exists in the object, including inherited properties.

6. Conclusion

In conclusion, TypeScript’s Record type and the various operations for retrieving, adding, modifying, and checking key existence provide developers with powerful tools to create and manipulate dynamic object structures while maintaining type safety. The ability to define specific key-value relationships enhances code clarity and prevents runtime errors associated with incorrect data types. Whether using classic iterations with for...in loops or modern methods like Object.entries(), TypeScript empowers developers to handle objects more efficiently. By incorporating these techniques, developers can build robust, maintainable codebases that benefit from TypeScript’s static typing features, fostering a more reliable and scalable development process.

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button