How to use Object.defineProperty In Typescript
The Object.defineProperty method allows us to define new properties directly on an object or modify existing properties. This method provides more control over property attributes such as configurable, enumerable, and writable.
Syntax:
Object.defineProperty(obj, 'name', {
value: 'JavaScript',
writable: true,
enumerable: true,
configurable: true
});
Example:
const obj: Record<string, any> = {};
Object.defineProperty(obj, 'name', {
value: 'JavaScript',
writable: true,
enumerable: true,
configurable: true
});
console.log("Before dynamic assignment:", obj.name);
obj.name = 'TypeScript';
console.log("After dynamic assignment:", obj.name);
Output:
"Before dynamic assignment:", "JavaScript"
"After dynamic assignment:", "TypeScript"
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