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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With