Can't use number as key in Typescript Map?

Viewed 652

In a class:

private stuff: Map<number, string> = new Map();

...

this.stuff[aNumber] = "hello";

Gives this error:

Element implicitly has an any type because expression of type number can't be used to index type Map<number, string>.

No index signature with a parameter of type number was found on type Map<number, string>

This makes no sense to me. Why doesn't Map<number, string> declare an index signature with a parameter of type number?

1 Answers

This is because Map is not using indexer - it's using get/set methods.

let foo: Map<number, string> = new Map();
foo.set(2, "something");
let some = foo.get(2);

What you could do is use number: string custom map object

let bar: { [key: number]: string } = {};
bar[1] = "some";
bar["sl"] = "some" // error

Please see playground.

Related