This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Examples of TypeScript

Content of this article: Enumerated types.Copy the code

Enumerated types are a common type in TypeScript. Using enumerations we can define constants with names. Use enumerations to clearly express intent or to create a differentiated set of use cases.

Digital enumeration

/ / 1
function getState(state) {
    if (state === 0) {
        return 'NORMAL'
    } else if (state === 1) {
        return 'LATE'
    } else if (state === 2) {
        return 'ABSENT'}}Copy the code

We can do this more elegantly in TypeScript. TypeScript provides an Enum syntax, which is called enumerated types. You’ve probably heard of enumerated types in other languages before, and you can use them in TypeScript today.

Defining enumeration types
/ / 2
enum Status {
    NORMAL,   / / normal
    LATE,     / / to be late
    ABSENT    / / miss
}
Copy the code

Example 2 uses the enum keyword to define an enumeration type. The value of NORMAL is 0, the value of LATE is 1, and the value of ABSENT is 2.

Using enumerated types
// Example 2
Status.LATE;    / / 1
Status[1];      // LATE reverses the type name
Copy the code

Using enumerations is simple: enumerators are accessed through their properties, and enumerations can also be accessed through their names.

Setting the initial value
/ / 4
enum Status {
    NORMAL = 1./ / normal
    LATE,         / / to be late
    ABSENT        / / miss
}
Copy the code

Enumerators start at 0 by default and increase in order. We can use an initializer and specify a constant for initialization. The value of a member that does not use an initializer is incremented by one. For example, in example 2, NORMAL is 1, LATE is 2, and ABSENT is 3.

/ / case 5
enum Status {
    NORMAL,       / / normal
    LATE = 10./ / to be late
    ABSENT        / / miss
}
Copy the code

Example 5: ABSENT (constant 10, LATE) NORMAL = 11 The answer is NORMAL is still 0.

String enumeration

In a string enumeration, each member must be initialized with either a string literal or another string enumeration member.

/ / case 6
enum Direction {
    East = "EAST",
    South = "SOUTH",
    West = "WEST",
    North = "NORTH",}Copy the code

String enumerations do not have the self-growing behavior of numeric enumerations, and naturally do not generate orientation maps like numeric enumerations do. String enumerations allow you to provide a value that is meaningful and readable at runtime, independent of the enumerator’s name.

Finish this! If this article helps you at all, please give it a thumbs up.