Sometimes, we want to dynamically assign properties to an object in TypeScript.
In this article, we’ll look at how to dynamically assign properties to an object in TypeScript.
How to dynamically assign properties to an object in TypeScript?
To dynamically assign properties to an object in TypeScript, we can define an interface that lets us accept any properties.
For instance, we write
interface MyType {
typesafeProp1? : number,
requiredProp1: string,
[key: string]: any
}
let obj: MyType;
obj = {
requiredProp1: "foo"
};
obj = {}
obj.typesafeProp1 = "bar"
obj.prop = "value";
obj.prop2 = 88;
to define the MyType
interface.
The interface stipulates that that the MyType
object can have the typesafeProp1
property and it’s a string.
It’s also requires the requiredProp1
property.
Also, we can add properties with keys other than the typesafeProp1
and requiredProp1
with [key: string]: any
.
Therefore, obj = {}
will give us a compile time error.
And obj.typesafeProp1 = "bar"
will also give us an error since 'bar'
isn’t a number.
Conclusion
To dynamically assign properties to an object in TypeScript, we can define an interface that lets us accept any properties.