[英]Javascript how to make object allow any key
In Angular (typescript), say I initiate this variable: 在Angular(打字稿)中,说我初始化了这个变量:
myVar = {}
Then I do a call that assigns this variable to a bigger object: 然后,我执行一个调用,将该变量分配给更大的对象:
... this.myVar = response
... 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 '{}'
. 例如,使用此代码, this.myVar.Name
将引发错误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 = {}
. 像myVar: any
一样myVar: any
工作,但是我仍然想至少将其声明为带有= {}
的对象。
I'm looking for something like {any}
or any{}
我正在寻找{any}
或any{}
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. 我认为您可以使用object
type ,它确实可以实现您想要的,即接受任何类型的键。 So the code would be: const yourVar: object = {};
因此代码如下: const yourVar: object = {};
以下应该工作
let myVar: any = {};
Just make it of type any
. 使其成为any
类型。
myVar: any;
Or better , you can make an interface to represent the type of myVar
, let's say that you have modal Product
which has properties: name, price, description etc...
and then myVar: Product
或者更好的是 ,您可以创建一个界面来表示myVar
的类型,假设您有一个模态Product
,该Product
具有以下属性: name, price, description etc...
,然后是myVar: Product
You could type it as an object with variable keys: 您可以使用可变键将其键入为对象:
let myVar: { [key: string]: any } = {};
that way you could add more fine-grained typings to the object. 这样,您可以向对象添加更多细粒度的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.