How does the hash variable syntax work in typescript?

后端 未结 2 1455
时光取名叫无心
时光取名叫无心 2020-12-09 15:13

...and where is it documented?

I\'ve seen examples like this around the place:

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


        
2条回答
  •  自闭症患者
    2020-12-09 15:20

    TypeScript Walkthrough: Interfaces

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

    The syntax for defining the index 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.

提交回复
热议问题