2016-09-07 3 views
17

Typescript에서 열거 형의 리터럴을 순환시키는 적절한 방법은 무엇입니까?Typescript : 라디오 버튼에 표시 할 enum 값을 반복하는 방법?

export enum MotifIntervention { 
    Intrusion, 
    Identification, 
    AbsenceTest, 
    Autre 
} 

export class InterventionDetails implements OnInit 
{ 
constructor(private interService: InterventionService) 
{ 
    let i:number = 0; 
    for (let motif in MotifIntervention) { 
     console.log(motif); 
    } 
} 

표시되는 결과가

0 
1 
2 
3 
Intrusion, 
Identification, 
AbsenceTest, 
Autre 

내가 루프 만 4 반복을 원하는가 목록입니다 : 나는 다음 열거있어

(현재 타입 스크립트 1.8.1을 사용하여) 열거 형에 4 개의 요소 만 있으므로 열거 형의 인덱스 번호로 보이는 0 1 2 및 3을 갖고 싶지 않습니다.

답변

45

두 가지 옵션 :

for (let item in MotifIntervention) { 
    if (isNaN(Number(item))) { 
     console.log(item); 
    } 
} 

또는

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key]))); 

(code in playground)

0 1 2 3 문자열이기 때문에

+0

그것은 작동하지 않습니다. – abreneliere

+4

그래서 isNaN (Number (...))에 대한 검사가 있습니다. 그것은 내가 공유 한 놀이터에서 작동합니다. –

+0

예, 작동했는데 뭔가 놓쳤을 것입니다. 중복 된 질문에없는 최상의 솔루션임을 알게되었습니다. – abreneliere