TypeScript - 如何将数组映射用于ES 6 Map?

Cer*_*ism 0 javascript dictionary typescript ecmascript-6

让我们说我有一组键值对象:

const data = [
    {key: "object1", value: "data1"},
    {key: "object2", value: "data2"},
    {key: "object3", value: "data3"},
]

const mappedData = data.map(x => [x.key, x.value]);

const ES6Map = new Map<string, string>(mappedData.values())
Run Code Online (Sandbox Code Playgroud)

如何将其转换为ES 6地图?它适用于JavaScript,但TypeScript会抱怨.在这里我得到了错误Argument of type 'IterableIterator<string[]>' is not assignable to parameter of type 'ReadonlyArray<[string, string]>'. Property 'length' is missing in type 'IterableIterator<string[]>'.

vib*_*97a 7

您需要执行type assertion并告诉typescript您mappedData的类型Array<[string,string]>而不是构造函数所需string[][]的子类型.Array<[any,any]>Map

const mappedData = data.map(x => [x.key, x.value] as [string, string]);
Run Code Online (Sandbox Code Playgroud)

代替

const mappedData = data.map(x => [x.key, x.value]);
Run Code Online (Sandbox Code Playgroud)

并且

values()按照评论中的指示放弃呼叫.