Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional array passed to new Map fails in typescript

Can't pass two dimensional array to new Map in Typescript:

 const myArray: string[][] = [['DE', 'Germany'], ['AU', 'Austria']];
 const myMap = new Map(myArray);

Fails to me with TS2769: No overload matches this call. Am I doing something wrong here?

TS Version 3.9.9

like image 403
Ren Avatar asked Feb 25 '21 15:02

Ren


People also ask

Is Map 2 dimensional array?

Map Method for 2-dimensional Arrays Also called a map within a map: Sometimes you'll come across a multidimensional array -- that is, an array with nested arrays inside of it.

Is it possible to declare a 2D array with different lengths?

You can't specify different sizes in the declaration.

How do you instantiate a map in TypeScript?

Use the Map() constructor to initialize a Map in TypeScript, e.g. const map1: Map<string, string> = new Map([['name', 'Tom']]) . The constructor takes an array containing nested arrays of key-value pairs, where the first element is the key and the second - the value. Copied!

How do you declare a bidimensional array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.


Video Answer


1 Answers

If you dig through the log, you'll see an error message of

Target requires 2 element(s) but source may have fewer.

The problem is that ['DE', 'Germany'] gets automatically type-widened to string[] - an array of strings, which may have two elements, or one, or zero - but the Map constructor requires such entry arrays to have at least 2 elements. The type information that the number of items in the array is 2 gets lost.

I'd put the array declaration on the same line as the new Map:

const myMap = new Map([['DE', 'Germany'], ['AU', 'Austria']]);

Another option is

const arr: [string, string][] = [['DE', 'Germany'], ['AU', 'Austria']];

to show that the array actually does have 2 items in it.

Also note that you can't have a variable name start with a number - start it with something else, probably a letter.

like image 92
CertainPerformance Avatar answered Oct 25 '22 00:10

CertainPerformance