Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Map Typescript

I'm trying to covert the following array to a Map:

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

What I have so far:

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'));

Do you know if this is something achievable?

PS: You can find Typescript playground here and the error that I'm getting

like image 732
Ricardo Rocha Avatar asked Apr 18 '26 01:04

Ricardo Rocha


1 Answers

obj.key is a string, and obj.value is a {num: number, letter: string}, so if you make an array of them ([obj.key, obj.value]), then you get an Array<string | {num: number, letter: string}>.

You need to tell TypeScript that you're creating a specific tuple, as expected by the Map constructor, not a generic array. There are a few ways of doing this:

// 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]));
like image 152
Josh Kelley Avatar answered Apr 19 '26 15:04

Josh Kelley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!