This page looks best with JavaScript enabled

Initialize empty object and add props

 ·   ·  ☕ 1 min read

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.

1
const planet = {};

Then, we add the props -

1
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.

1
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 -

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

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

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

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

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things