Thursday, April 26, 2018

How do I find the index of an enum in TypeScript when all of the options have string settings?

What if we changed up the Nordic enum as shown here like so?

enum Nordic {
   Denmark = 'Denmark',
   Finland = 'Finland',
   Iceland = 'Iceland',
   Norway = 'Norway',
   Sweden = 'Sweden'
}

 
 

What would sabotage the code then, wouldn't it?

let noTrees: number = Nordic['Iceland'];
alert(noTrees);

 
 

I don't see a way around this in order to get a numeric index short of looping through the enum values as suggested here while incrementing a counter and having some conditionally logic to assign the counter off to another variable at the right time.

No comments:

Post a Comment