2017-09-21 125 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

感謝您的快速響應! 我把問題簡化了很多,實際的錯誤似乎在別的地方。你介意看看更新的問題嗎? –