Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 993
Jochen Kühner Avatar asked Sep 08 '16 09:09

Jochen Kühner


People also ask

What is dictionary called in TypeScript?

A collection of key and value pairs is called a dictionary in TypeScript. The dictionary is also referred as a map or a hash. A map can be created by using the type Map and the keyword new.

How do you represent a dictionary in JSON?

JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .

What is the type of a JSON object in TypeScript?

In Typescript, there are two types of objects. Plain objects: When we try to parse JSON data using JSON. parse() method then we get a plain object and not a class object. Class(constructor) objects: A class object is an instance of a Typescript class with own defined properties, constructors and methods.


1 Answers

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;
}
like image 55
Fenton Avatar answered Sep 21 '22 08:09

Fenton