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
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.
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 { } .
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With