Sunday, March 5, 2017

using enums in TypeScript takes some getting used to

enum Nordic {
   Denmark,
   Finland,
   Iceland,
   Norway,
   Sweden
}
let noTrees: number = Nordic['Iceland'];
alert(noTrees);
alert(Nordic[noTrees]);
let highestStandardOfLiving: Nordic = 3;
alert(highestStandardOfLiving);
alert(Nordic[highestStandardOfLiving]);

 
 

This code will cause four alerts which sequentially will contain the following:

  1. 2
  2. Iceland
  3. 3
  4. Norway

 
 

And, respectively, these four alerts show off:

  1. how to fish out a value from an enum with a magic string
  2. how to fish out the string value from an enum with a number
  3. how to set a enum with a number
  4. how to fish out the string value from an enum with the enum setting

 
 

Note that the line up above reading...

let highestStandardOfLiving: Nordic = 3;

 
 

...could become...

let highestStandardOfLiving: Nordic = Nordic.Norway;

 
 

...and the four alerts would be the same. Also note that when you talk from exclusively JavaScript into TypeScript as you might in Angular 1 with Angular 2 hodgepodges you have to set enums by just using the number encoding. There is no way to set with a friendly name in the name of readable code from the JavaScript side.

No comments:

Post a Comment