2017-09-21 126 views
0

我试图枚举映射到一个字符串:枚举到字符串查找对象 - >没有索引签名

enum Status { 
    NEW = "NEW", 
    INPROCESSING = "IN PROCESSING", 
    DONE = "DONE" 
}; 

const statusToColor: { [key in Status ]: string } = { 
    "NEW": "blue", 
    "IN PROCESSING": "yellow", 
    "DONE": "green" 
} 

到现在为止一切都很好。 但当我尝试:

编辑:似乎我简化了问题太多,作为实际问题似乎仍然是别的地方:

的没有索引错误只发生,当我尝试从数组喂 “statusToColor”,是这样的:

const statusArrayToColors = (statusArray: Status[]): string[] => { 
    return statusArray.map(status => statusToColor[status]) 
} 

在这种情况下

statusToColor[status] 

根据编译器没有索引签名。

+0

您是否看到我的答案?你编辑修改错字的代码适合我。 – lilezek

回答

2

您的代码有错字。这个工作对我来说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]; 

检查的statusToColor行。要定义类型,您必须使用冒号:,不等于=

注意:you need at least typescript version 2.4.

+0

其新版本的2.4字符串文字可用于Enums – rjustin

+0

感谢您的快速响应! 我把问题简化了很多,实际的错误似乎在别的地方。你介意看看更新的问题吗? –