4

I am new to typescript. I have a map in typescript like below:

const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')
...

I am trying to convert mapping to type '{ [key: string]: string; }'

How to do that in typescript?

2 Answers 2

7

Simply do:

Object.fromEntries(mapping)

Reference:


Complete example:

const mapping = new Map<string, string>()

mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')

console.log(mapping)

// { [key: string]: string } is same as Record<string, string>
const record: { [key: string]: string } = Object.fromEntries(mapping)

console.log(record)
Sign up to request clarification or add additional context in comments.

Comments

1

You can define an empty object with the new mapping.

Use the Map forEach() to iterate over the keys.

const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion');
mapping.set('meat', 'chicken');
mapping.set('drink', 'beer');

console.log(mapping);

const newMapping : { [key : string] : string} = {};

mapping.forEach((val,key) => {
newMapping[key] = val;
});

console.log(newMapping);

Playground Link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.