Marty Pitt
Marty Pitt

Reputation: 29290

Typescript : Using number as key in map

This answer suggests it's valid to declare a map which enforces a number as a key.

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

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

numberMap generates the following compiler error:

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

What's the correct way to declare this?

Upvotes: 7

Views: 12005

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221024

I'm not 100% sure if this is a bug or not (I'd need to check the spec), but it's definitely OK to do this as a workaround:

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

If something's indexable by number you'd usually use [] instead of {}, but that's obviously up to you.

Upvotes: 11

Related Questions