How To Dynamically Add Properties to an Object in TypeScript

In JavaScript, we can easily dynamically add properties to an object, but for TypeScript, there are strict rules about data types, so to do this, we will use some of the ways provided by TypeScript, such as: using index signature and using Record utility. Let’s start

Ways to dynamically add properties to an object in TypeScript

To dynamically add properties to an object in TypeScript, we can use some of the ways that TypeScript has provided, such as using the index signature or using the Record utility.

Using index signature

When we cannot predict the data type structure in an object, we can use the index signature to dynamically add properties to an object, by declaring a data type for the key and declaring the type. data for value, dynamic attributes when added according to the structure predefined in the index signature

Example:

interface Student {
    // Use index signature to pre-declare key and value data types
    [key: string]: any;
}

// Create a new student object
const student: Student = {};

// Dynamically add properties to student objects
student.id = 12;
student.name = "John";
student.age = 20;
student.major = "Software technology";

// Print the object to the console
console.log(student);

Output:

{ id: 12, name: 'John', age: 20, major: 'Software technology' }

In the above example, we declare an interface for the purpose of creating a blueprint for student objects. In this interface, we use the index signature to pre-declare the data type of the key, which is a string, and the data type of value is any, so the object created by this interface will get dynamic properties according to such structure. Then we create a new student object, and add dynamic properties to it.

Using Record utility

Another way to dynamically add properties to an object in TypeScript is to use the Record utility, which works similarly to the index signature, but with a difference in syntax.

Example:

// Using the Record utility to predefine the data type of key and value pairs
const student: Record<string, any> = {};

// Dynamically add properties to student objects
student.id = 12;
student.name = "John";
student.age = 20;
student.major = "Software technology";

// Print the object to the console
console.log(student);

Output:

{ id: 12, name: 'John', age: 20, major: 'Software technology' }

Summary

In summary, to dynamically add properties to an object in TypeScript, we will use index signature or Record utility. These are two common easy-to-use ways that TypeScript provides us. We often use the index signature method because there can be declared directly inside the object. Hope this post is useful to you

Leave a Reply

Your email address will not be published. Required fields are marked *