2017-11-25 136 views
0

打字稿中是否可以在枚举中使用字符串变量? 我可以使用字符串枚举这样的:在打字稿的枚举中使用字符串变量

enum AllDirections { 
    TOP = 'top', 
    BOTTOM = 'bottom', 
    LEFT = 'left', 
    RIGHT = 'right', 
} 

但这代码:

const top: string = 'top' 
const bottom: string = 'bottom' 
const left: string = 'left' 
const right: string = 'right' 

enum AllDirections { 
    TOP = top, 
    BOTTOM = bottom, 
    LEFT = left, 
    RIGHT = right, 
} 

结果与错误:Type 'string' is not assignable to type 'AllDirections'

+0

为什么要'顶部*'和*'AllDirections.TOP'? – jonrsharpe

+0

这只是一个错误重现的例子。事实上,我试图从一个文件中导入一个包含所有可用操作的redux动作类型列表,并将它们分配给另一个文件中的枚举,以便能够使用此枚举类型作为reducer中的类型。 – Anton

回答

1

如果你真的想这样做,那么你可以断言值为any

enum AllDirections { 
    TOP = top as any, 
    BOTTOM = bottom as any, 
    LEFT = left as any, 
    RIGHT = right as any 
} 

该pr与此相关的是,如果您将这些分配给字符串值,则需要对字符串进行断言。这不是理想:

let str: string = AllDirections.TOP as any as string; 

或者,这是一个有点冗长,但如果你想成员有正确的类型,你可以考虑使用对象:

// remove the explicit string types so that these are typed 
// as their string literal values 
const top = 'top'; 
const bottom = 'bottom'; 
const left = 'left'; 
const right = 'right'; 

type AllDirections = Readonly<{ 
    TOP: typeof top, 
    BOTTOM: typeof bottom, 
    LEFT: typeof left, 
    RIGHT: typeof right 
}>; 

const AllDirections: AllDirections = { 
    TOP: top, 
    BOTTOM: bottom, 
    LEFT: left, 
    RIGHT: right 
}; 

另一种选择是翻转其中字符串存储:

enum AllDirections { 
    TOP = 'top', 
    BOTTOM = 'bottom', 
    LEFT = 'left', 
    RIGHT = 'right', 
} 

const top = AllDirections.TOP; 
const bottom = AllDirections.BOTTOM; 
const left = AllDirections.LEFT; 
const right = AllDirections.RIGHT; 
+0

第二种解决方案对我来说很完美。谢谢! – Anton