typescript 将数组转换为Map类型脚本

hs1ihplo  于 2023-01-31  发布在  TypeScript
关注(0)|答案(1)|浏览(826)

我正在尝试将以下数组转换为Map:

const arr = [
  { key: 'user1', value: { num: 0, letter: 'a' } },
  { key: 'user2', value: { num: 0, letter: 'b' } },
  { key: 'user3', value: { num: 0, letter: 'c' } },
];

我目前掌握的情况:

const arr = [
  { key: 'user1', value: { num: 0, letter: 'a' } },
  { key: 'user2', value: { num: 0, letter: 'b' } },
  { key: 'user3', value: { num: 0, letter: 'c' } },
];
const b = arr.map(obj => [obj.key, obj.value]);
const map = new Map<string, { num: number; letter: string }>(b);

console.log(map.get('user1'));

你知道这是不是可以实现的吗?

  • PS:你可以在这里找到TypescriptPlayground和我得到的错误 *
abithluo

abithluo1#

obj.key是一个stringobj.value是一个{num: number, letter: string},所以如果你把它们组成一个数组([obj.key, obj.value]),那么你会得到一个Array<string | {num: number, letter: string}>
你需要告诉TypeScript你正在创建一个特定的元组,正如Map构造函数所期望的那样,而不是一个泛型数组。有几种方法可以做到这一点:

// The simplest: Tell TypeScript "I mean exactly what I said."
// (This makes it readonly, which isn't always desirable.)
const b = arr.map(obj => [obj.key, obj.value] as const);

// Or be explicit in a return type. You can do this at a few levels.
const b = arr.map<[string, { num: number, letter: string}]>(obj => [obj.key, obj.value]);
const b = arr.map((obj): [string, { num: number, letter: string}] => [obj.key, obj.value]);

// Or, as explained in the comments, do it in one line, and TypeScript
// can infer tuple vs. array itself.
const map = new Map(arr.map(obj => [obj.key, obj.value]));

相关问题