How to assign dynamic properties to an object in typescript
- Admin
- Oct 3, 2023
- Typescript
In javascript, you can create an object using object syntax.
var employee = {};
And assign the properties dynamically.
employee.name = "john";
You can access the dynamic properties as given below.
console.log(employee.name); // john
If you use the save above code in Typescript.
var employee = {};
employee.name = "john";
console.log(employee.name);
It gives a below error.
Property 'name' does not exist on type '{}'.
In typescript, a variable declared is typed, which means the declared variable should have a type and causes an error at compile time.
It provides type safety at compile time to avoid an error.
In that case, How do you add dynamic properties to an object?
How to add dynamic properties to an object in typescript?
There are multiple ways we can do
-using any type
In this, Declare an object of type any
which accepts any type of data.
var employee: any = {};
employee.name = "john";
console.log(employee.name);
You have to write code to convert from any to desired and add extra time to do it. This is not followed type safety and defeats the purpose of doing in typescript.
- Using interface index type signature
Index type signature allows you to store key values and values with the declared type.
interface Employee {
[key: string]: any;
}
Above, the interface is declared with string
keys and value types any
.
Create an object of the interface as follows
var obj: Employee = {};
You can assign only string keys with any value.
obj.name = "ram";
obj.salary = 5000;
console.log(obj); //{ "name": "ram", "salary": 5000}
You can inline index signatures with short syntax.
var obj: { [k: string]: any } = {};
obj.name = "ram";
obj.salary = 5000;
console.log(obj); //{ "name": "ram", "salary": 5000}
-using Record Type
Typescript introduced Record<K, V>
is an object with key types K and value types, T.
this object can store the string
key and value any
type
var emp1: Record<string, any> = {};
emp1.name = "ram";
emp1.salary = 5000;
console.log(emp1);
- extend Interface
This is a cleaner way of doing type safety and object inheritance. Creates a base interface that has common properties
interface BaseObject {
id: string;
name: string;
}
You can create a new interface by extending the base interface with additional required properties.
interface Employee extends BaseObject {
salary: string;
}
Create an object of the interface to which you can add properties
var emp1: Employee = {};
emp1.name = "john";
This gives a cleaner and reusable approach for users to extend object behavior.
Conclusion
To sum up, You learned multiple ways to add dynamic properties to an object in typescript with examples.
- any type
- index type
- record type
- extend interface
I prefer to extend it as a reusable and cleaner object in terms of reuse and type safety.