[英]Enum to String Lookup Object -> has no index Signature
I'm trying to map an enum to a String: 我正在尝试将枚举映射到字符串:
enum Status {
NEW = "NEW",
INPROCESSING = "IN PROCESSING",
DONE = "DONE"
};
const statusToColor: { [key in Status ]: string } = {
"NEW": "blue",
"IN PROCESSING": "yellow",
"DONE": "green"
}
Up to this point everything is fine. 到目前为止,一切都很好。 But when I try:
但是当我尝试:
EDIT: Seems as I simplified the problem to much, as the actual problem still seems to be somewhere else: 编辑:似乎我将问题简化了很多,因为实际问题似乎仍然存在于其他地方:
The has no Index error only occurs, when I try to feed "statusToColor" from an Array, like this: 当我尝试从数组中馈送“ statusToColor”时,只会发生没有索引错误,如下所示:
const statusArrayToColors = (statusArray: Status[]): string[] => {
return statusArray.map(status => statusToColor[status])
}
In this case 在这种情况下
statusToColor[status]
has no Index signature according to the compiler. 根据编译器,没有索引签名。
Your code has a typo. 您的代码有错字。 This works for me
Version 2.5.0-dev.20170629
: 这适用于我
Version 2.5.0-dev.20170629
:
enum Status {
NEW = "NEW",
INPROCESSING = "IN PROCESSING",
DONE = "DONE"
};
const statusToColor: { [key in Status ]: string } = {
"NEW": "blue",
"IN PROCESSING": "yellow",
"DONE": "green"
}
const color: string = statusToColor[Status.NEW];
Check the line of statusToColor
. 检查
statusToColor
行。 To define the type you must use colon :
, not equal =
. 要定义类型,必须使用冒号
:
,不等于=
。
Note: you need at least typescript version 2.4. 注意: 您至少需要打字稿版本2.4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.