Yuchen
Yuchen

Reputation: 33036

Error of "Element implicitly has an 'any' type because expression of type can't be used to index type" when when updating value of Map

This snippet wants to assign a value to a dictionary of type key being string and value being number.

let dict: Map<string, number> = new Map<string, number>();
dict["one"] = 1;

Element implicitly has an 'any' type because expression of type '"one"' can't be used to index type 'Map'. Property 'one' does not exist on type 'Map'.Vetur(7053)

What does this error means? How do we fix it?

Upvotes: 0

Views: 641

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

While a Map instance is an object, the proper way to use it as a data structure is to call .set and .get to set and get values:

dict.set('one', 1);

console.log(dict.get('one'));

Maps aren't supposed to have arbitrary key-value pairs on the instance like you're doing, hence the TS error.

Also, TS can infer the type of the Map just fine from the expression on the right - no need for an explicit annotation. Also, unless you're planning on reassigning the Map (which is generally a pretty odd thing to want to do), it should be declared with const:

const dict = new Map<string, number>();

Upvotes: 2

Related Questions