Jochen Kühner Jochen Kühner - 2 months ago 25
TypeScript Question

Typescript -> To what cast a Dictionary from Json.net

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

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;
}
Comments