Hello, this is a more literal challenge. This is the 8th day of my participation in the August More Text Challenge
– Ts introduces a new concept for JS called Enums, let’s see how to use it.
Enums: full Enumerations
Used to define constants with names. Use enumerations to clearly express intent or to create a differentiated set of use cases. TypeScript supports numeric and string-based enumerations.
Note: TS supports enumeration of numbers and strings
Define enums variables: start with the enums keyword,Variable name (uppercase)
enum Pet {
Dog,
Cat,
Goldfish
}
Copy the code
Now, the default Dog value is 0,Cat value is 1,… And so on, the default values are self-increasing
1. Now if you gave Dog a default value, what would the following value be?
enum Pet {
Dog=4,
Cat,
Goldfish
}
Copy the code
Now Dog is 4,Cat is 5… Assign the following values in a self-increasing fashion
2. What if you don’t want them to grow? You can assign a value to each of them
enum Pet {
Dog=4,
Cat=2,
Goldfish=34
}
Copy the code
Now Dog has a value of 4,Cat has a value of 2 and piranhas has a value of 34, all of which are numeric types
3. Enum values can also be strings
enum Pet {
Dog="hahah", the Cat = "lalal," Goldfish = "enenen}"Copy the code
Now the value of Dog is hahah, the value of Cat is lalal, and Goldfish is enenen, all of which are strings
4. Can Enum values be mixed with strings and numbers? Theoretically possible, but not recommended
enum Pet {
Dog="hahah",
Cat=44, Goldfish = "enenen}"Copy the code
This is not recommended
4. The value of Enum can also befunction
, but if there is only one function, put itThe last one
, otherwise, it willerror
Note: The function must have a return value
getName(){
return 22
}
Copy the code
// the following is wrong ❌
enum Pet {
Dog=getName(),
Cat,
Goldfish
}
Copy the code
// The following is true
enum Pet {
Dog,
Cat,
Goldfish=getName()
}
Copy the code
Now, the default value of Dog is 0,Cat is 1, and Piranhas is 22
5. Enum can be calculated
enum Animal {
Head,
Eye,
Leg
}
enum People {
Head: Animal.Head,
Eye:1+1.Leg:2*2.Mouth:Head
}
Copy the code
Animal Head = 0,Eye = 1,Leg = 2, People = 2 The value of Head is 0, the value of Eye is 2, the value of Leg is 4, and the value of Mouth is 0
conclusion
- Why enum?
Enums makes code more semantic and more maintainable
- When to use it?
The value of the variable is within a fixed range, for example: traffic light, there are only three. Grade 1 to 9. Up, down, left, and right on the keyboard, there are only four keys… , and so on, which have a fixed range can be defined as enum types
Hope you enjoy this article about the introduction to TS enums!!