Search code examples
javascriptobjectinitialization

Javascript how to make object allow any key


In Angular (typescript), say I initiate this variable:

myVar = {}

Then I do a call that assigns this variable to a bigger object:

... this.myVar = response

Then when I want to access something on this changed object, I keep getting errors that the keys don't exist. For example with this code this.myVar.Name would throw the error Property "Name" does not exist on type '{}'. How can I just bypass this error?

Something like myVar: any does the job, but I would still like to at least declare it as an object with something like = {}.

I'm looking for something like {any} or any{}


Solution

  • This is an issue for typescript types, and for that I would recommend adding a tag for typescript in your question. I think you can use the object type, it does exactly what you want, that is accept any kind of key. So the code would be: const yourVar: object = {};