2016-09-26 64 views
2

我不知道如果我可以使用枚舉作爲接口的對象鍵.. 我已經建立了一個小測試吧:使用枚舉爲打字稿界面鍵

export enum colorsEnum{ 
red,blue,green 
} 

export interface colorsInterface{ 
[colorsEnum.red]:boolean, 
[colorsEnum.blue]:boolean, 
[colorsEnum.green]:boolean 
} 

當我運行它,我」 m得到以下錯誤:

A computed property name in an interface must directly refer to a built-in symbol. 

我做錯了或它只是不可能?

回答

4

要定義一個接口,必須提供成員名稱而不是計算。

export interface colorsInterface { 
    red: boolean; 
    blue: boolean; 
    green: boolean; 
} 

如果你擔心保持枚舉和同步接口,你可以使用以下命令:

export interface colorsInterface { 
    [color: number]: boolean; 
} 

var example: colorsInterface = {}; 
example[colorsEnum.red] = true; 
example[colorsEnum.blue] = false; 
example[colorsEnum.green] = true; 

打字稿是完全爲你高興的枚舉傳遞的索引和rename-例如,如果您決定重命名red,那麼重構會將所有內容保存在一起。