2017-11-25 1 views
0

typescript에서 열거 형에서 문자열 변수를 사용할 수 있습니까? I는 다음과 같이 열거에서 문자열을 사용할 수 있습니다typescript의 enum에서 문자열 변수 사용

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

왜 'top' * 및 *'AllDirections.TOP'을 원하십니까? – jonrsharpe

+0

이것은 오류 재현을위한 예입니다. 사실 나는 가능한 모든 동작을 포함하는 하나의 파일에서 redux 작업 유형 목록을 가져 와서이 파일을 감속기에서 유형으로 사용할 수 있도록 다른 파일의 열거 형에 할당하려고합니다. – Anton

답변

1

당신이 정말로 이렇게 할 경우에, 당신은을 주장 할 수를 값 : 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

두 번째 솔루션은 저에게 완벽합니다. 고맙습니다! – Anton