简体   繁体   中英

Typescript Map Relation with Array objects

Accordint to MDN doc

initializing a Map from an array like this is legitimate:

let kvArray = [['key1', 'value1'], ['key2', 'value2']];
let myMap: Map<string, string> = new Map(kvArray);

Despite, my Visual Studio Code compiler complains with this:

No overload matches this call.
Overload 1 of 3, '(iterable: Iterable<readonly [string, string]>): Map<string, string>', gave the following error.
Argument of type 'string[][]' is not assignable to parameter of type 'Iterable<readonly [string, string]>'.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.

The problem is that you havn't put a type on kvArray , so typescript is inferring it. It infers that it's a string[][] , but that's not specific enough. The Map constructor needs tuples with exactly two strings, not arrays with an arbitrary number of strings. Your javascript is creating these tuples, but you'll need to be explicit about the types:

let kvArray: [string, string][] = [['key1', 'value1'], ['key2', 'value2']];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM