如何访问包含' - '的对象的字段人物

时间:2017-01-26 20:55:32

标签: javascript json typescript

我有一个看起来像这样的JSON对象:

"stats": {
    "task-stats": {
        "throughput": 0
    },
    "node-stats": {
        "from1": {
            "avg_exec_time_ns": 10504,
            "collected": 2108636,
            "emitted": 2108636
        }
    }
}

我从网络服务获取对象,并使用JSON.parse。我希望能够将这些字段用短划线声明为TypeScript Interface,但我不知道该怎么做。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

interface Stats {
    "task-stats": {
        throughput: number
    }
    "node-stats": {
        from1: {
            avg_exec_time_ns: number,
            collected: number,
            emitted: number
        }
    }
}

如何使用它:

var stats: Stats;
stats["task-stats"].throughput // OK
stats["node-stats"].from1 // OK