How to Dynamically Assign Properties to an Object in TypeScript

To dynamically assign properties to an object in TypeScript, you can use the “index notation” or the “Object.assign()” method. 

Method 1: Using the index notation

In this approach, you first create an object with an index signature, allowing it to have any property with a string key and value. Then, you use index notation to assign a value to a property with a dynamic name.

You use square brackets([ ]) to access and set a property on the Object using a variable as the property name. This is a simple way to assign properties dynamically to an object.

Example

const obj: { [key: string]: any } = {};

const propertyName = "dynamicProperty";
const propertyValue = "Hello, TypeScript!";

obj[propertyName] = propertyValue;
console.log(obj);

Output

{ dynamicProperty: 'Hello, TypeScript!' }

In this example, we created an object obj with an index signature { [key: string]: any }, which means it can have any property with a string key and any value.

In the next step, we used the index notation (obj[propertyName]) to assign a value to a dynamically-named property.

Method 2: Using the Object.assign() function

The Object.assign() function creates a new object by merging two other objects. The first Object is typically empty, while the second contains the dynamic property name and its associated value.

By using computed property names (enclosed in square brackets([ ])) in the second Object, you can dynamically assign the property name.

The Object.assign() function then merges the two objects, resulting in a new object with the desired dynamic property.

This approach creates a new object instead of modifying an existing one, which may be helpful in cases where immutability is essential.

Example

const propertyName = "dynamicProperty";
const propertyValue = "Yello, Homer!";

const obj = Object.assign({}, { [propertyName]: propertyValue });
console.log(obj);

Output

{ dynamicProperty: 'Yello, Homer!' }

In this example, we used the Object.assign() function to create a new object by merging an empty object ({}) and an object with the dynamically-named property ({ [propertyName]: propertyValue }). This way, the new Object has the dynamic property with the assigned value.

Both methods allow you to assign properties to objects in TypeScript dynamically, and the choice between them depends on your specific use case and coding style preferences.

Leave a Comment