Initialize a Map containing arrays in TypeScript


Typescript Problem Overview

I want to make a Map where each member contains an array of strings. But how do I initialize and type it (in a single statement)?

(naively) I tried this:

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

and I get:

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[]>'.

Typescript Solutions

Solution 1 - Typescript

Per Mozilla's Map documentation, you can initialize as follows:

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

Solution 2 - Typescript

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

To push elements into Map:

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

To get/retrieve elements from map:

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

Or directly use

variableName: Map<string, string[]> = new Map("a", ["b", "c"]);


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBBaysingerView Question on Stackoverflow
Solution 1 - TypescriptGPicazoView Answer on Stackoverflow
Solution 2 - TypescriptManjunath HadimaniView Answer on Stackoverflow