初始化包含数组的Map

时间:2017-01-20 18:14:12

标签: typescript

我想创建一个Map,其中每个成员都包含一个字符串数组。但是我如何初始化并输入它(在单个语句中)?

我试过这个:

  private _gridOptions:Map<string, Array<string>> = {"1": ["test"]};

我得到了:

Module build failed: Error: /Users/*****/Work/dashboard/src/app/core/pg.service.ts (8,5): Type '{ "1": string[]; }' is not assignable to type 'Map<string, string[]>'.

2 个答案:

答案 0 :(得分:53)

Mozilla's Map documentation,您可以按如下方式进行初始化:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

答案 1 :(得分:1)

variableName: Map<string, string[]> = new Map();

将元素推入 Map:

variableName.set("a", ["b", "c"]);

从地图中获取/检索元素:

variableName.get(key);// "a" in above case