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.
|
|
Then, we add the props -
|
|
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.
|
|
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 -
|
|
Or, if you can, change the prop assignment to a more dynamic property assignment do the below -
|
|
The dynamic assignment functions just like Javascript and you don’t have any type advantages.