0

I am trying to find a simple way to implement a Dictionary in TypeScript 1.8. There are several implementation suggestions on the web, but the most attractive looks like this:

var MyDictionary: { [id: number]: string };

Unfortunately, I don't really understand what this code means. MyDictionary is of type { [id: number]: string }, but what on earth does that mean? And, in turn, what does [id: number]: string mean? Is this also a type? I am guessing the id is the key, but the value appears to be nameless.

How do I, for example, iterate over the dictionary and extract the key/value pairs? I use underscore.js quite liberally in my code so suggestions for iteration and manipulation using this library appreciated.

serlingpa
  • 12,024
  • 24
  • 80
  • 130
  • Oo, indexable type, perfect answer thank you! But how would one go about iterating over such a collection, retrieving both the 'key' (or index?) and value? – serlingpa May 20 '16 at 18:03
  • Aha http://stackoverflow.com/questions/16174182/typescript-looping-through-a-dictionary. I shall try this. Pity you didn't answer the question, I could've marked it as "answered". – serlingpa May 20 '16 at 18:04

1 Answers1

0

That's the right construct to use for a dictionary; it's called an indexable type (or indexer) and the docs can be found here.

The basic concept is to overlay type constraints on a plain JS object, using the object key names as dictionary keys and specifying the type of objects it contains. As such, you can use standard JS object iteration techniques like for...in for indexable types.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471