Jochen Kühner Jochen Kühner - 1 year ago 147
TypeScript Question

Typescript -> To what cast a Dictionary from

If I use Json.Net a Dictionary is serialized as:

"key": "value",
"key2": "value2",

How can I cast this to a Typescript object?
i'd mostly like a array of typeof value

Answer Source

A Dictionary can be expressed gracefully in TypeScript using the following interface:

interface IDictionary {
    [index:string]: string;

You can use it like this:

var example: IDictionary = {
    "key1": "value1",
    "key2": "value2"

var value1 = example["key1"];

The general dictionary allows any collection of key/value pairs, so you don't need to explicitly describe the exact combination, this makes it very similar to the dictionary at the source (i.e. it won't promise to have a value for a given key).

You can make it as complex as you like... or even generic:

interface IDictionary<T> {
    [index:string]: T;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download