Last updated: Feb 28, 2024
Reading timeยท3 min
To define a Map with array values in TypeScript, type the Map to have keys of a specific type and set the values to have an array type.
All of the key-value pairs in the Map must conform to the specified type.
const map1 = new Map<number, string[]>([ [0, ['a', 'b']], [1, ['c', 'd']], ]); map1.set(2, ['e', 'f']); // ๐๏ธ ['e', 'f'] console.log(map1.get(2));
We used a generic to type the Map
object
to have keys of type number
and values of type string[]
.
You can pass arrays of key-value pairs to the map if you want to initialize the Map with values.
const map1 = new Map<number, string[]>([ [0, ['a', 'b']], [1, ['c', 'd']], ]); // โ Works map1.set(2, ['e', 'f']); // โ๏ธ Error: Argument of type 'string' is // not assignable to parameter of type 'string[]'.ts(2345) map1.set(3, 'bobbyhadz.com');
We tried to add a value of type string
to a Map
object that expects an array
of strings.
Here is an example of how to declare a Map that has an array of objects as values.
type Employee = { name: string; salary: number; }; const map1 = new Map<number, Employee[]>([ [ 0, [ { name: 'Alice', salary: 100 }, { name: 'Bobby Hadz', salary: 150 }, ], ], ]); const arr: Employee[] = []; arr.push({ name: 'Carl', salary: 200 }); arr.push({ name: 'Dean', salary: 250 }); map1.set(1, arr); // ๐๏ธ [{name: 'Carl', salary: 200}, {name: 'Dean', salary: 250}] console.log(map1.get(1));
The keys in the Map are of type number
because that's the first type we passed
to the generic when defining the Map
object. The values are of type
Employee[]
.
get()
method to get a Map value by a key, the type of the value is possibly undefined
.TypeScript can't be sure that a value with the specified key exists in the Map.
I've also written an article on how to iterate over a Map in TS.
You can use a type guard to make sure the value isn't undefined
before
accessing elements at an index or properties on an object.
type Employee = { name: string; salary: number; }; const map1 = new Map<number, Employee[]>([ [ 0, [ { name: 'Alice', salary: 100 }, { name: 'Bobby Hadz', salary: 150 }, ], ], ]); map1.set(1, [{ name: 'Carl', salary: 200 }]); // ๐๏ธ const result: Employee[] | undefined const result = map1.get(1); // โ If statement as a type guard if (result !== undefined) { console.log(result[0]); // ๐๏ธ {name: 'Carl', salary: 200} } // โ Optional chaining as a type guard console.log(result?.[0]?.name); // ๐๏ธ "Carl"
The if
condition serves as a
type guard because TypeScript knows
that the result
variable is an array in the if
block.
You can also use the
optional chaining (?.) operator, which
short-circuits instead of throwing an error if the reference is null
or
undefined
.
You can learn more about the related topics by checking out the following tutorials: