How does the hash variable syntax work in typescript?
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.
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.