Initialize empty object and add props

There are situations when you need to initialize object without props. How do you manage that it Typescript?

Let’s consider the example below. First, we declare the object and initialize it to an empty object.

const planet = {};

Then, we add the props -

planet.name = "earth";

The above initialization + assignment combination is perfectly valid in Javascript.

But Typescript does not agree with planet.name since the object was declared as type {} (an empty object).

Ideally, the fix will be to declare and initialize with the actual props.

const planet = { name: "earth" };

But, this is not always possible. You may also have to interact with Javascript or migrate large chunks of code, which makes the process more challenging.

A quick fix to the problem is to simply do -

const planet = {} as any;
planet.name = "earth";

Or, if you can, change the prop assignment to a more dynamic property assignment do the below -

const planet = {};
planet["name"] = "earth";

The dynamic assignment functions just like Javascript and you don’t have any type advantages.

comments powered by Disqus