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:
- 2
- Iceland
- 3
- Norway
And, respectively, these four alerts show off:
- how to fish out a value from an enum with a magic string
- how to fish out the string value from an enum with a number
- how to set a enum with a number
- 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