2016-09-26 58 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,那么重构会将所有内容保存在一起。