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!
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.
map() does not change the original array. It will always return a new array.
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.
Return Value: This method returns the created array. Below examples illustrate the Array map() method in TypeScript.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With