How to Dynamically Assign Properties to an Object in TypeScript
-
Use the
as
Keyword to Add Dynamic Properties to an Object in TypeScript -
Use the
Partial
Type to Dynamically Add Properties to an Object in TypeScript -
Use the
?
Operator to Dynamically Add Properties to an Object in TypeScript
TypeScript is a strongly typed language, and hence every variable and object must have a type. Thus dynamically adding properties to an already defined variable is difficult; however, there are some ways by which it can be done.
This tutorial will focus on how dynamic properties can be added to an object.
Use the as
Keyword to Add Dynamic Properties to an Object in TypeScript
TypeScript follows strict typing for every variable. However, one can use the as
keyword to force the compiler to infer the type of a variable as the given type even if all the type fields are not present in the object.
In this way, further adding dynamic properties to the object is possible. The following code segment shows how this can be done in the case of an empty object.
interface Person {
name : string;
age : number;
country : string;
id : number;
}
// forcing the compiler to infer person as of type Person
var person : Person = {} as Person;
// dynamically adding types
person.id = 1;
person.country = "India";
person.name = "Ramesh";
console.log(person);
Output:
{
"id": 1,
"country": "India",
"name": "Ramesh"
}
Instead of an empty object, one can also have certain fields present like var person : Person = { id : 1 } as Person
.
Use the Partial
Type to Dynamically Add Properties to an Object in TypeScript
The Partial
type is used to make all attributes of an interface optional. The Pick
type is used when only certain interface attributes are required to create the object.
The Omit
type is used as the inverse of the Pick
type - to remove certain attributes from the interface while keeping all the other attributes as required.
interface Animal {
legs : number ;
eyes : number ;
name : string ;
wild : boolean ;
};
// we define a variable with partial types
var dogWithAllOptionalTypes : Partial<Animal> = {
eyes: 2
};
// Now, further properties can be added to the object when needed
dogWithAllOptionalTypes.legs = 4;
dogWithAllOptionalTypes.wild = false;
Use the ?
Operator to Dynamically Add Properties to an Object in TypeScript
The ?
operator behaves very similarly to the Partial
type. The user must explicitly make the fields in a type or interface optional using the ?
operator.
The following is the code segment using the previous example to show the implementation.
interface Animal {
legs : number ;
eyes? : number ;
name? : string ;
wild? : boolean ;
};
var dog : Animal = {
legs : 4
};
// Now further properties can be added to the object when needed
dog.eyes = 2;
dog.wild = false;
Thus in the example above, the field legs
is compulsory, while the other optional fields can be added when needed.