Typescript & # 8594; What distinguishes a dictionary from Json.net

If I use Json.Net, the dictionary serializes as:

{
    "key": "value",
    "key2": "value2",
    ...
}

How can I pass this to a Typescript object? I liked the typeof value array the most

+4
source share
3 answers

A dictionary can be easily expressed in TypeScript using the following interface:

interface IDictionary {
    [index:string]: string;
}

You can use it as follows:

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

var value1 = example["key1"];

The general dictionary allows any set of key / value pairs, so you do not need to explicitly describe the exact combination, this makes it very similar to the dictionary in the source (that is, it does not promise to have a value for the given key).

, ... :

interface IDictionary<T> {
    [index:string]: T;
}
+4

, , :

interface MyJsonResponse {
    key: string;
    key2: string;
    ...
}

let json: MyJsonResponse = getResponse(); // {"key":"value","key2":"value2",...}
0

here is a way to define an existing class and get an instance of the same for web applications.

let data = {"key":"value","key2":"value2", "key3":"value3"}

class InstanceLoader {
    static getInstance<T>(context: Object,className :string, data: Object) : T {
        var instance = Object.create(context[className].prototype);
        Object.keys(data).forEach(x=>{
            instance[x] = data[x];
        });
        return <T> instance;
    }
}

class MyDictionary {
}

let example = InstanceLoader.getInstance<MyDictionary>(window,'MyDictionary',data);
console.log(JSON.stringify(example));

**Output: {"key":"value","key2":"value2","key3":"value3"}**
0
source

Source: https://habr.com/ru/post/1653988/


All Articles