如何在 TypeScript 中合并 Map

要在 TypeScript 中合并map:

  1. 显式键入第三个 Map 的键和值。
  2. 使用扩展语法 (…) 解包前两个 Map 的键值对。
  3. Map 的键和值的类型必须匹配。
const map1 = new Map([['country', 'Germany']]);
const map2 = new Map([['salary', 100]]);

const map3 = new Map<string, string | number>([...map1, ...map2]);

// ?️ {'country' => 'Germany', 'salary' => 100}
console.log(map3);

我们使用泛型来键入第三个 Map 对象的键和值。

我们可以对前两个 Map 做同样的事情,但它不是必需的,因为 TypeScript 能够根据传入的值推断类型。

以下代码片段实现了相同的结果。

const map1 = new Map<string, string>([['country', 'Germany']]);
const map2 = new Map<string, number>([['salary', 100]]);

const map3 = new Map<string, string | number>([...map1, ...map2]);

// ?️ {'country' => 'Germany', 'salary' => 100}
console.log(map3);

第一个 Map 具有字符串类型的键和字符串类型的值。

第二个 Map 具有字符串类型的键和数字类型的值。

在合并 Map 时,我们必须确保第三个 Map 的类型与其他两个 Map 的类型一致。

该示例显示了我们如何必须使用联合类型将第三个映射的值设置为字符串或数字。

我们使用扩展运算符 (...) 将 2 个 Map 对象中的键值对解包到一个数组中。

const map1 = new Map<string, string>([['country', 'Germany']]);

// ?️ [ ['country', 'Germany'] ]
console.log([...map1]);

该数组包含由键值对组成的嵌套数组。

最后一步是将数组传递给 Map() 构造函数,该构造函数将一个可迭代对象作为参数。

设置好值后,示例如下所示:

const map3 = new Map<string, string | number>([
  ['country', 'Germany'],
  ['salary', 100],
]);

可迭代的 Map 必须由键值对组成,例如 一个二维数组或另一个 Map 对象。

只要最终 Map 的类型与其他 Map 的类型一致,就可以根据需要对尽可能多的 Map 对象重复此过程。

const map1 = new Map<string, string>([['country', 'Germany']]);
const map2 = new Map<string, number>([['salary', 100]]);
const map3 = new Map<string, boolean>([['isProgrammer', true]]);

const map4 = new Map<string, string | number | boolean>([
  ...map1,
  ...map2,
  ...map3,
]);

第四个 Map 中的值类型必须与所有其他 Map 中的值类型兼容。

请注意,保留键的插入顺序。 如果我们需要重新排序键值对,只需切换使用扩展运算符 (…) 的顺序即可。