Typescript: using a number as a key on a map

This answer assumes that it is valid to declare a card that presses number as the key.

However, when I try the following in the playground , I get an error message.

 class Foo { stringMap: { [s: string]: string; } = {}; numberMap: { [s: number]: string; } = {}; } 

numberMap generates the following compiler error:

Unable to convert '{}' to '{ [s: number]: string; }' '{ [s: number]: string; }' : Index signatures types '{}' and '{ [s: number]: string; }' '{ [s: number]: string; }' incompatible {}

What is the right way to declare this?

+4
source share
1 answer

I am not 100% sure if this is an error or not (I will need to check the specification), but it is definitely OK to do this as a workaround:

 class Foo { stringMap: { [s: string]: string; } = {}; numberMap: { [s: number]: string; } = <any>{}; } 

If something is indexed by number, you usually use [] instead of {} , but this is clearly up to you.

+10
source

All Articles