1

I want to convert a Typescript Map to an object. The following code shows a compiler error:

const sourceMap = new Map<string, string>();
sourceMap.set('foo', 'bar');

const jsonObject = {};
sourceMap.forEach((value, key) => {
    jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Playground Link

The compiler doesn't like the line jsonObject[key] = value; saying:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.(7053)

How can I fix that or what am I doing wrong here?

1 Answer 1

2

You can add an explicit type annotation to jsonObject to allow indexing with any string. The predefined type Record should work fine:

const sourceMap = new Map<string, string>();
sourceMap.set('foo', 'bar');

const jsonObject: Record<string, string> = {};
sourceMap.forEach((value, key) => {
    jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Playground Link

Sign up to request clarification or add additional context in comments.

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.