2017-11-25 190 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