Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the hash variable syntax work in typescript?

Tags:

typescript

...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.

like image 777
Doug Avatar asked Jan 12 '14 02:01

Doug


People also ask

What is a Hash in TypeScript?

TypeScript Hashes can be defined as an interface , which stores elements with either string or number indexes. JavaScript allows for mixing index types, but TypeScript requies it to be one or the other.

How will you declare a variable in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

What is @types in TypeScript?

What is a type in TypeScript. In TypeScript, a type is a convenient way to refer to the different properties and functions that a value has. A value is anything that you can assign to a variable e.g., a number, a string, an array, an object, and a function. See the following value: 'Hello'


2 Answers

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.

like image 60
JLRishe Avatar answered Sep 28 '22 08:09

JLRishe


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.

like image 26
meagar Avatar answered Sep 28 '22 09:09

meagar