Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Can't construct new Map() with return from mapping function

I have this code (only relevant parts here):

interface Page {
  name: String;
  displayName: String;
}


let pages: Page[] = [{name: 'x', displayName: 'y'}, {name: 'a', displayName: 'b'}];
let m = new Map(pages.map(page => [page.name, page.displayName]));

And I get this error for it (from tslint):

Argument of type 'String[][]' is not assignable to parameter of type 'Iterable<[{},{}]>'

These types are defined as such:

map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

interface MapConstructor {
    new <K, V>(): Map<K, V>;
    new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
    prototype: Map<any, any>;
}

(both types are from here)

What am I doing wrong?
Thanks!

like image 279
Ben Avatar asked May 19 '15 06:05

Ben


People also ask

Why is map returning undefined Javascript?

The map() method returns undefined values when we forget to explicitly return a value in the callback function we passed to the method. Make sure to return a value from the callback function to not get any undefined values in the array.

Does map function need return?

map() does not change the original array. It will always return a new array.

How do I create a map map in TypeScript?

Creating a MapUse Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.

What does map return in TypeScript?

Return Value: This method returns the created array. Below examples illustrate the Array map() method in TypeScript.


1 Answers

What am I doing wrong?

Nothing. The TypeScript type inference system is struggling a bit, help it along with a type annotation to tell it that you mean a tuple[string,string] not a multi dimensional array string[][]:

var pages:{
  name: string;
  displayName: string;
}[];

var pagesForMap = pages.map((page):[string,string] => [page.name, page.displayName]);
var pagesNames = new Map(pagesForMap);

Tuple types are covered here : http://basarat.gitbooks.io/typescript/content/docs/types/type-system.html

like image 154
basarat Avatar answered Oct 11 '22 01:10

basarat