EN
TypeScript - enum type
5
points
In TypeScript it is possible to create enum type in following ways.
1. Automatic numeric enum
members example
enum Color
{
Red, // 0
Green, // 1
Blue // 2
}
let blue : Color = Color.Blue;
console.log(Color.Red);
console.log(Color.Green);
console.log(blue);
Output:
0
1
2
2. Computed and constant enum
members example
enum Mode
{
Read = 1 << 1,
Write = 1 << 2,
Both = Read | Write
}
let read : Mode = Mode.Read;
console.log(read);
console.log(Mode.Write);
console.log(Mode.Both);
Output:
2
4
6
3. Assigned numeric enum
members example - auto counting
enum Value
{
Two = 2,
Three, // 3
Four, // 4
Six = 6,
Seven // 7
}
let two : Value = Value.Two;
console.log(two);
console.log(Value.Three);
console.log(Value.Seven);
Output:
2
3
7
4. String enum
members example
enum Pet {
Dog = 'Dog',
Cat = 'Cat',
Rabbit = 'Rabbit'
}
let dog : Pet = Pet.Dog;
console.log(dog);
console.log(Pet.Cat);
console.log(Pet.Rabbit);
Output:
Dog
Cat
Rabbit
5. Generating logic enum
members example
let counter = 0;
enum Key {
A = counter *= 2,
B = counter *= 2,
C = counter *= 2
}
let a : Key = Key.A;
console.log(a);
console.log(Key.B);
console.log(Key.C);
Output:
1
2
3
6. Heterogeneous enum
members example - strings + numbers
enum Mix {
Drink = 1,
Food = 2,
Sweet = '1/3',
Normal = '2/3',
Sour = '3/3'
}
let drink : Mix = Mix.Drink;
console.log(drink);
console.log(Mix.Sweet);
console.log(Mix.Sour);
Output:
1
1/3
3/3