By using the index signature of the object
The index signature is also a way of explicitly typing an object but in a different syntax than the simple explicit typing.
Syntax:
const obj_name: { [key_name: key_type]: index_sign_type } = {}
Example:This example shows the way of explicitly typing an object using the object index signature.
const obj: { [name: string]: any } = {
name: "Sachin Tendulkar"
}
console.log("Before dynamic assignment: ", obj.name)
obj.name = "Virat Kohli";
console.log("Before dynamic assignment: ", obj.name)
Output:
Before dynamic assignment: Sachin Tendulkar
After dynamic assignment: Virat Kohli
How do I dynamically assign properties to an object in TypeScript?
In TypeScript, we can not assign the properties dynamically to an object directly by using the dot operator and the square brackets syntax which we generally use to assign dynamic properties in Vanilla JavaScript.
JavaScript is a dynamically typed language and the type of a variable is determined at runtime due to which assigning dynamic properties to JavaScript objects does not give any error. On the other hand, TypeScript is a statically typed language, and the type of variable must be predefined in this. Therefore, if you try to assign dynamic properties to a TypeScript object directly using the dot operator and square bracket syntax will give an error.
Defining an object with empty curly ({}) brackets in TypeScript is not considered as an object, it will be considered as empty braces, and assigning properties to it will throw an error. In this article, we will discuss different methods of dynamically assigning a property to an object in TypeScript.
There are three ways of assigning dynamic properties to objects in TypeScript:
Table of Content
- By declaring the object with explicit type
- By using the index signature of the object
- By using the Record Utility Type
- Using Object.defineProperty