How To Define A Map With Array Values In TypeScript

Define a Map with Array values in TypeScript

Let’s find out the information we provided in this post. You will know how to Define a Map with Array values in TypeScript.

Define a Map with Array values in TypeScript

I would first instantiate a Map object and use a generic to type it to have keys of any type you want and values ​​as an array.

In this example, we have a Map object with the data type of keys as ‘number’ and the data type of values ​​as an array of numbers.

const myMap = new Map<number, number[ ]>([
  [0, [1, 2]],
  [1, [3, 4]],
]);
 
myMap.set(2, [5, 6, 7]);
myMap.set(3, [8]);
myMap.set(4, []);
 
console.log(myMap)

Output:

Map (5) {0 => [1, 2], 1 => [3, 4], 2 => [5, 6, 7], 3 => [8], 4 => []} 

We got a map with five elements in the output. Each element is a key-value pair of type number and number[].

Note: If you intentionally add a value of type ‘number’ instead of an array of numbers, you will get an error.

myMap.set(5,9) //this line causes an error

Output:

error: Argument of type 'number' is not assignable to parameter of type 'number[]'.

In case you have an object and you want to initialize a Map that has values as an array of objects. See the following example:

type Children = {
  name: string;
  age: number;
  gender: string;
};
 
const myMap = new Map<number, Children[]>([
  [
    0,
    [
      { name: 'Dave', age: 8, gender: 'Male' },
      { name: 'Mary', age: 6, gender: 'Female' },
    ],
  ],
]);
 
const childs: Children[] = [];
 
childs.push({ name: 'Tom', age: 10, gender: 'Male' });
childs.push({ name: 'Suzy', age: 9, gender: 'Female' });
 
myMap.set(1, childs);
 
console.log(myMap);

Output:

Map (2) {0 => [{
  "name": "Dave",
  "age": 8,
  "gender": "Male"
}, {
  "name": "Mary",
  "age": 6,
  "gender": "Female"
}], 1 => [{
  "name": "Tom",
  "age": 10,
  "gender": "Male"
}, {
  "name": "Suzy",
  "age": 9,
  "gender": "Female"
}]} 

As a result, you have a Map object, and the values have the Children[] as type.

Summary

You have just seen how we can Define a Map with Array values in TypeScript. Create your own example to test and see the results.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *