typescript 打字稿:在地图中使用数字作为键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14994406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript : Using number as key in map
提问by Marty Pitt
This answersuggests it's valid to declare a map which enforces a number
as a key.
这个答案表明声明一个强制 anumber
作为键的映射是有效的。
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:
numberMap
生成以下编译器错误:
Cannot convert
'{}'
to'{ [s: number]: string; }'
: Index signatures of types'{}'
and'{ [s: number]: string; }'
are incompatible{}
无法转换
'{}'
为'{ [s: number]: string; }'
:类型的索引签名'{}'
并且'{ [s: number]: string; }'
不兼容{}
What's the correct way to declare this?
声明这一点的正确方法是什么?
回答by Ryan Cavanaugh
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:
我不是 100% 确定这是否是一个错误(我需要检查规范),但将其作为解决方法绝对可以:
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.
如果某些内容可以按数字索引,您通常会使用[]
代替{}
,但这显然取决于您。