Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : Using number as key in map

Tags:

typescript

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?

like image 583
Marty Pitt Avatar asked Feb 21 '13 04:02

Marty Pitt


1 Answers

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.

like image 112
Ryan Cavanaugh Avatar answered Sep 23 '22 03:09

Ryan Cavanaugh