2017-11-25 15 views
0

typecriptでは列挙型で文字列変数を使用できますか? 私はこのような列挙型で文字列を使用することができます:あなたは本当にこれをしたい場合は、あなたが主張する可能性がType 'string' is not assignable to type 'AllDirections'typescriptの列挙型で文字列変数を使用

+0

なぜ「top' *」と「 'AllDirections.TOP'」が必要ですか? – jonrsharpe

+0

これはエラー再現の単なる例です。実際には、すべての使用可能なアクションを含む1つのファイルからreduxアクションタイプのリストをインポートしようとしています。このエミュレートをレデューサーのタイプとして使用できるように、別のファイルのenumに割り当てています。 – Anton

答えて

1

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, 
} 

結果値:any

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

これをoblemとすると、これらを文字列値に割り当てると、文字列にアサーションが必要になります。それは理想的ではないのです。

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

2番目の解決策は私にとって完璧です。ありがとうございました! – Anton

関連する問題