Skip to content
Advertisement

Get property of initially empty object after adding properties

I am trying to make a data converting script (with Angular) and need to access properties of an object which is initially empty (see simplified code below). However, I get an error message that says that the key does not exist in the object. I can not add the keys when initialising the object because the data might be different in the next run. I have tried different methods of accessing the key but I have not yet figured it out. I hope someone can help me!

TS7053: Element implicitly has an ‘any’ type because expression of type ‘1’ can’t be used to index type ‘{}’.   Property ‘1’ does not exist on type ‘{}’.

JavaScript

Advertisement

Answer

If you don’t know the property names at first, you can use any. Initialize it like this:

JavaScript

If you know the property types (e.g. all the properties are strings), then you can type it something like this:

JavaScript

Then it will work.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement