Open In App

TypeScript Enums Type

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Enums Type is not natively supported by Javascript, but it’s a notable feature of the Typescript Programming language. In general, enumerations shortly called “enum” are available in most programming languages to create named consonants. Enums allow us to create a set of named constants, making it easier for us by being self-explanatory while declaring a set of predefined values.

Syntax:

enum enum_name {
    constant_name = value,
    ... so on
}

Parameters:

  • enum is the keyword itself which is used to start the enum.
  • enum_name is the name given to the enum type variable.
  • constant_name is the variable name that should be declared inside of the enum.
  • value is the value given to that constant_name variable.

Different types of the Enums:

  • Numeric enum: In numeric enums, we can declare the first value, after that all of the following members are auto-incremented by one from that point on.
  • String enum: String enums also follow a similar concept, but have some subtle runtime differences. In string enums, we don’t have the concept of auto-incrementing, but it has benefits like giving a meaningful and readable value when your code runs by “serializing” and independent of the enum member itself.
  • Heterogenous Enums: We can mix up the constant datatype with string and number members, but it is not advisable to do so. Generally, a set of predefined constants will always be the same datatype. To declare a heterogenous enum, initialize constants with different data types like string and number while declaring the enum.
  • Computed and Constant members: Each enum member can either be a constant or computed value. To be a constant value it has to satisfy any of the three following conditions, if any of the expressions doesn’t fall under any of the three rules then it will be a computed member.
    • It is the first member of the enum and it has no initializer, so by default, it is assigned 0.
    • Members which have no initializer but the previous constants are numeric constants.
  • Union enums and enum member types: Within constant enum sets, there exists a unique category known as “literal enum members.” These members do not require computation and fall into one of these two categories:
    • Enums at runtime:
      • They have no assigned value, remaining uninitialized.
      • Their values are initialized using string literals like “apple,” “banana,” or “cherry.”
      • They are initialized with numeric literals, such as 5, 42, or by applying a unary minus to a numeric literal (e.g., -7 or -99).
    • Enums at compile time: Even though, enums are exists as objects at runtime, the “keyof” keyword works differently than its usual behaviour with a typical object. To make the “keyof” to respond to a enum like a typical object, we have to append a one more keyword “typeof” to get the type that represents all the enum keys as strings.
  • Ambient enums: It is used to create a already existing enum type enum.
  • Objects vs Enums: Objects and enums have distinct roles in programming. Objects embody specific instances within a class, whereas enums establish a collection of named, unchanging values.

Example 1: In this example, we will use the numeric enums to store the discount percentage for various cards in a enum, as the discount are tends to be constant storing inside a enum increases the readability and understandability of the code.

Javascript




// Discount percentage enum
// set of constants of
// discounts based on type of card
enum discount {
    STANDARD = 0.05,
    GOLD = 0.1,
    PLATINUM = 0.2,
    DIAMOND = 0.3,
}
 
// Function to get the net
// cost after the discount
function
    getNetCost(cardTYpe: string,
        amount: number): number {
    if (cardTYpe === "GOLD") {
        return amount -
            (amount * discount.GOLD)
    } else if (cardTYpe === "PLATINUM") {
        return amount -
            (amount * discount.PLATINUM)
    } else if (cardTYpe === "DIAMOND") {
        return amount -
            (amount * discount.DIAMOND)
    } else {
        return amount -
            (amount * discount.STANDARD)
    }
}
 
// calculating the net cost with the function
// and logging the result value
console.log(getNetCost("PLATINUM", 1000))


Output:

ts_numeric_enums_example1

Numeric Enum Example

Example 2: In this example, we will use the String enums to store a set of predefined string literals under a enum.

Javascript




// Typescript code for String enums
 
// Department enum contains
// various department string literals
 
enum Department {
    CSE = "COMPUTER SCIENCE ENGINEERING",
    IT = "INFORMATION TECHNOLOGY",
    MECH = "MECHANICAL ENGINEERING"
}
 
// Initializing the myDepartment
// const with enum value or get choice
// from user and pick value based on those
// from enum
const myDepartment: Department = Department.IT
 
// Logging out my department value
console.log(`My department is ${myDepartment}`)


Output:

ts_enums_example2

String Enums example

Conclusion: Enums can be used to create more readable and self-explanatory code, especially when dealing with sets of constants. However, it’s important to be aware that enums are compiled to JavaScript and can introduce some runtime overhead. Additionally, numeric enums can sometimes lead to unexpected behavior if not used carefully, so it’s a good practice to assign values explicitly to enum members when necessary.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads