How does the hash variable syntax work in typescript?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

...and where is it documented?

I've seen examples like this around the place:

class MyThing {   private _layers: { [id: string] : SimpleLayer } = {};   ... } 

...and that works, which is great, but the syntax is confusing to me.

What is 'id'? Why is the syntax not just blah:{string:SimpleLayer}, which doesnt work. I've also seen {[name: string]:Type} and {[index:string]:Type}.

I've been looking over typescriptlang.org trying to find where this is actually documented, but I can't seem to find it at all.

回答1:

http://blogs.msdn.com/b/typescript/archive/2013/01/24/interfaces-walkthrough.aspx

See the section "Describing an Indexable Object". This is called an index signature.

The syntax is:

[Identifier: KeyType]: ValueType 

KeyType can be either string or number.

You could claim that the Identifier isn't really needed since it doesn't get used anywhere, but I think it's required in order to force the class/interface designer to indicate what the hash map key should represent (an id, name, e-mail address, etc.). This also provides the possibility of having intellisense show the hash key name (as Visual Studio does for other languages), though I don't think Typescript intellisense currently provides this.



回答2:

Regarding your question of why the syntax isn't simpler, specifically something like blah:{string:SimpleLayer}:

Because this would be ambiguous. This syntax already exists and has meaning:

var x: { string: SimpleLayer } 

This declares a variable x. The type of x has one property, named string, which is of type SimpleLayer. If I wanted to use x, I would do this:

x.string = new SimpleLayer; 

It's more obvious if we use a real example:

var circle: {radius: number} 

This declares a variable with one property (radius) that is of type number, it does not declare a hash mapping radius types to number types.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!