简体   繁体   English

与数组对象的打字稿映射关系

[英]Typescript Map Relation with Array objects

Accordint to MDN doc根据MDN 文档

initializing a Map from an array like this is legitimate:从这样的数组初始化 Map 是合法的:

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

Despite, my Visual Studio Code compiler complains with this:尽管如此,我的 Visual Studio Code 编译器还是抱怨:

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.问题是您没有在kvArray上放置类型,因此打字稿正在推断它。 It infers that it's a string[][] , but that's not specific enough.它推断它是一个string[][] ,但这还不够具体。 The Map constructor needs tuples with exactly two strings, not arrays with an arbitrary number of strings. Map 构造函数需要正好有两个字符串的元组,而不是具有任意数量字符串的数组。 Your javascript is creating these tuples, but you'll need to be explicit about the types:您的 javascript 正在创建这些元组,但您需要明确类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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