最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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

Share Improve this question edited Sep 8, 2016 at 10:24 Maximilian Riegler 23.5k4 gold badges65 silver badges73 bronze badges asked Sep 8, 2016 at 9:44 Jochen KühnerJochen Kühner 1,4113 gold badges21 silver badges50 bronze badges 1
  • Today it should be casted to Record<string, string> – Jochen Kühner Commented Dec 4, 2022 at 18:01
Add a comment  | 

3 Answers 3

Reset to default 18

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

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

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"}**

With the limited code and explantation that you gave it should be:

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

let json: MyJsonResponse = getResponse(); // {"key":"value","key2":"value2",...}
发布评论

评论列表(0)

  1. 暂无评论